Plot benchmark results with Matplotlib

Vincent Bernat

In the past week, I ran a lot of bench­marks us­ing a Spirent Avalanche which is an ap­pli­ance pro­vid­ing per­for­mance test­ing of net­work-re­lated prod­ucts (a load bal­ancer, a router, a web server, …). The re­port­ing mod­ule does not pro­vide a lot of flex­i­bil­ity and the plots are not the most beau­ti­ful ones. For­tu­nately, the re­sults are also ex­ported as CSV.

Mat­plotlib is a Python plot­ting li­brary which pro­duces great fig­ures with­out mak­ing things hard when they should be easy. It is a good re­place­ment for gnu­plot and you don’t need a lot of Python knowl­edge to use it. The doc­u­men­ta­tion in­cludes a fine user’s guide that should get you started in less than 20 minutes.

Up­date (2017-04)

This ar­ti­cle is quite old and cov­ers an out­dated ver­sion of Mat­plotlib.

Quick introduction#

You can use Mat­plotlib from IPython to ex­periment:

$ ipython -pylab
Python 2.6.7 (r267:88850, Jul 10 2011, 08:11:54)
Type "copyright", "credits" or "license" for more information.

  Welcome to pylab, a matplotlib-based Python environment.
  For more information, type 'help(pylab)'.

> In [1]: plot([1,1,4,5,10,11])

When you are ready, you can build a sim­ple Python script:

#!/usr/bin/env python
from matplotlib.pylab import *
plot([1,1,4,5,10,11])
savefig("my-plot.pdf")

Grabbing results from CSV#

Data are con­tained in a file named realtime.​csv. It con­tains the raw data as well as some gen­eral in­for­ma­tion about the bench­mark (test name, de­scrip­tion, pa­ram­e­ters…). We need to skip them. For­tu­nately, csv2rec() al­lows us to load data from a CSV file into a record ar­ray and skip the first rows if necessary.

from matplotlib.pylab import *
import sys, os
import gzip

skip = 0
for line in gzip.open(sys.argv[1]):
    if line.startswith("Seconds Elapsed,"):
        break
    skip = skip + 1
ava = csv2rec(gzip.open(sys.argv[1]),skiprows=skip)

Now, the “Elapsed sec­onds” col­umn can be ac­cessed with ava['elapsed_​seconds'].

General structure#

I need 4 plots:

  • suc­cess­ful, un­suc­cess­ful and at­tempted trans­ac­tions per second,
  • min­i­mum, av­er­age and max­i­mum re­sponse time per page,
  • Avalanche CPU usage,
  • in­com­ing and out­go­ing bandwidth.

The most im­por­tant plot is the first one. The sec­ond one is less im­por­tant and the last ones are here only to check we did not hit some bot­tle­neck dur­ing the bench­mark. We want to pro­duce a page like this:

General structure
General plot layout

Mat­plotlib al­lows us to plot sub­fig­ures. We cre­ate 4 sub­fig­ures shar­ing the same X axis (which is the num­ber of sec­onds elapsed since the be­gin­ning of the bench­mark). We save the re­sult to PDF.

# Create the figure (A4 format)
figure(num=None, figsize=(8.27, 11.69), dpi=100)

ax1 = subplot2grid((4, 2), (0, 0), rowspan=2, colspan=2)
# […]
ax2 = subplot2grid((4, 2), (2, 0), colspan=2, sharex=ax1)
# […]
ax3 = subplot2grid((4, 2), (3, 0), sharex=ax1)
# […]
ax4 = subplot2grid((4, 2), (3, 1), sharex=ax1)
# […]

# Save to PDF
savefig("%s.pdf" % TITLE)

Bandwidth plot#

Let’s start with the eas­i­est plot: band­width usage.

# Plot 4: Bandwidth
ax4 = subplot2grid((4, 2), (3, 1), sharex=ax1)
plot(ava['seconds_elapsed'], ava['incoming_traffic_kbps']/1000.,
     'b-', label='Incoming traffic')
plot(ava['seconds_elapsed'], -ava['outgoing_traffic_kbps']/1000.,
     'r-', label='Outgoing traffic')
grid(True, which="both", linestyle="dotted")
ylabel("Mbps", fontsize=7)
xticks(fontsize=7)
yticks(fontsize=7)

Here, in the sub­plot po­si­tioned in (3,1), we plot the num­ber of sec­onds elapsed ver­sus the in­com­ing traf­fic with a blue line (b-). We also plot the sec­onds elapsed ver­sus the out­go­ing traf­fic with a red line (r-).

Here is the result:

Bandwidth plot
Bandwidth plot

Most func­tions of Mat­plotlib are ex­posed as a method of the ob­ject they re­fer to and as a global func­tion. In the lat­ter case, the func­tion is ap­plied to the lat­est cre­ated fig­ure or plot­ting area. For ex­am­ple, plot() is called as a func­tion and there­fore refers to the plot­ting area ax4. We could have writ­ten ax4.​plot() instead.

CPU plot#

The av­er­age CPU uti­liza­tion data avail­able in the CSV file needs to be nor­mal­ized. We as­sume the Avalanche to be mostly idle on start. The plot­ting part is pretty sim­i­lar to our pre­vi­ous case.

# CPU
max = np.max(ava['average_cpu_utilization'])
order = 10**np.floor(np.log10(max))
max = np.ceil(max/order)*order
cpu = (max - ava['average_cpu_utilization'])*100/max

# Plot 3: CPU
ax3 = subplot2grid((4, 2), (3, 0), sharex=ax1)
plot(ava['seconds_elapsed'],
     cpu,
     'r-', label="Avalanche CPU")
grid(True, which="both", linestyle="dotted")
ylabel("Avalanche CPU%", fontsize=7)
xticks(fontsize=7)
yticks(fontsize=7)

Response time#

We would like to plot re­sponse time. We have three cor­re­spond­ing met­rics: min­i­mum re­sponse time, av­er­age re­sponse time, max­i­mum re­sponse time. Be­cause these met­rics start from 0 ms up to sev­eral sec­onds, a log­a­rith­mic scale is used:

# Plot 2: response time
ax2 = subplot2grid((4, 2), (2, 0), colspan=2, sharex=ax1)
plot(ava['seconds_elapsed'], ava['minimum_response_time_per_page_msec'],
     'b-', label="Minimum response time")
plot(ava['seconds_elapsed'], ava['maximum_response_time_per_page_msec'],
     'r-', label="Maximum response time")
plot(ava['seconds_elapsed'], ava['average_response_time_per_page_msec'],
     'g-', linewidth=2, label="Average response time")
legend(loc='upper left', fancybox=True, shadow=True, prop=dict(size=8))
grid(True, which="major", linestyle="dotted")
yscale("log")
ylabel("Response time (msec)", fontsize=9)
xticks(fontsize=9)
yticks(fontsize=9)

This is also the first graphic with a legend.

Response time plot
Response time plot

Transactions per second#

The most im­por­tant plot is the num­ber of trans­ac­tions per second.

# Plot 1: TPS
ax1 = subplot2grid((4, 2), (0, 0), rowspan=2, colspan=2)
plot(ava['seconds_elapsed'], ava['desired_load_transactionssec'],
     '-', color='0.7', label="Desired Load")
plot(ava['seconds_elapsed'], ava['successful_transactionssecond'],
     'g:', label="Successful")
plot(ava['seconds_elapsed'], smooth(ava['successful_transactionssecond']),
     'g-', linewidth=2)
plot(ava['seconds_elapsed'], ava['attempted_transactionssecond'],
     'b-', label="Attempted")
plot(ava['seconds_elapsed'], ava['aborted_transactionssecond'],
     'k-', label="Aborted")
plot(ava['seconds_elapsed'][:-1], ava['unsuccessful_transactionssecond'][:-1],
     'r-', label="Unsuccessful")
legend(loc='upper left', fancybox=True, shadow=True, prop=dict(size=10))
grid(True, which="both", linestyle="dotted")
ylabel("Transactions/s")

The num­ber of suc­cess­ful trans­ac­tions is plot­ted twice: when the bench­marked equip­ment be­comes over­loaded, we get a lot of noise in this met­ric and it can be dif­fi­cult to read. There­fore, we plot a smoothed ver­sion with the help of NumPy:

import numpy as np
def smooth(x, win=4):
    s = np.r_[x[win-1:0:-1],x,x[-1:-win:-1]]
    w = np.ones(win, 'd')
    y = np.convolve(w/w.sum(),s,mode='valid')
    return y[(win-1)/2:-(win-1)/2]

np.​r_() is just here to ex­tend our data by the size of the win­dow. np.​ones() builds a weight vec­tor of the size of the win­dow. If the win­dow is 4, we get [0.25, 0.25, 0.25, 0.25]. We use this vec­tor to ap­ply a con­vo­lu­tion to the orig­i­nal data. Here is the result:

Transactions plot
TPS plot

The orig­i­nal data is a green dot­ted line while the smoothed one is a green thick line. What about the three an­no­ta­tions? Mat­plotlib al­lows us to put an­no­ta­tions on a fig­ure. Here is how it is done:

# Noticeable points
count = 0
def highlight(index, reason):
    global count
    if index and index > 0:
        x,y = (ava['seconds_elapsed'][index],
               smooth(ava['successful_transactionssecond'])[index])
        plot([x], [y], 'ko')
        annotate('%d TPS\n(%s)' % (y,reason), xy=(x,y),
                 xytext=(20, -(count+4.7)*22), textcoords='axes points',
                 arrowprops=dict(arrowstyle="-",
                 connectionstyle="angle,angleA=0,angleB=80,rad=10"),
                 horizontalalignment='left',
                 verticalalignment='bottom',
                 fontsize=8)
        count = count + 1

highlight(np.argmax(smooth(ava['successful_transactionssecond'])), "Max TPS")
highlight(np.argmax(cpu > 99), "CPU>99%")
highlight(np.argmax(ava['average_response_time_per_page_msec'] > 500), ">500ms")
highlight(np.argmax(ava['average_response_time_per_page_msec'] > 100), ">100ms")

np.​argmax() re­turns the in­dex of the first max­i­mum value. The trick here is that when I write ava['average_​response_​time_​per_​page_​msec'] > 100, I get an ar­ray with 1 when the value is more than 100 and 0 oth­er­wise. There­fore, np.​argmax() will re­turn the first in­dex where the value is su­pe­rior to 100 ms.

The highlight() func­tion will add a point (plot([x], [y], 'ko')) on the smoothed suc­cess­ful trans­ac­tions per sec­ond plot and add an an­no­ta­tion with some fancy arrow.

Look at this bench­mark of ng­inx as TLS ter­mi­na­tion for a com­plete out­put of this script.