Matt's Blog: while { coding }
    Back to Matt's Homepage   |   Hire Matt


Two weeks ago, after falling prey to a vicious and unprovoked nerdsniping, I ended up creating a little tool for measuring how fast Python code runs. This week I spent an afternoon wrestling with Python packaging and managed to release my tool as SwissTime.

Measuring how long code takes to run is not exactly unexplored country. Still, nothing I found seemed to fit my needs. A profiler was overkill. Other timing tools wanted to measure one thing at a time. I wanted to run my code and at the end see a tidy little report of times for each chunk of code. Here’s what the output looks like:

Time in seconds
1.095976 | Startup
0.117262 | Load input image
0.018422 | Build masks
0.117944 | Populate layers
0.015563 | Build layers
0.019718 | Tone down green
0.092624 | Convert to floats
0.341209 | Resize
0.006941 | Image adjustments
0.056750 | Convert to bytes
0.916881 | Save as PNG

In this particular example I’ve labeled each chunk of code in an image conversion script. This report tells me how fast each chunk is. For example, I can see that the dominating times for this script are startup (over 1 second) and the final conversion of the output PNG (nearly 1 second). In an earlier incarnation of this script those times seemed very small because the dominating chunk of code was “Populate layers”, which took 12 seconds!

You can install SwissTime with pip like so:

pip install swisstime

Here is what typical usage looks like:

import swisstime

# Do some things
swisstime.tick("I did some things!")

# Do some more things
swisstime.tick("Even more things happened!")


(Alternatively you can just call to get a list of time/label tuples that you can use to analyze times over many runs.)