Note: this blog post is the first I am undertaking with the IPython Notebook. I am still playing with formatting and so on, so please bear with me if the content doesn't seem as easy to read as it should. The notebook itself can be found as a gist file on Github and you can alternatively view it using the online Notebook viewer.

I want to discuss a typical bit of Python, taken from a program sent me by a colleague (whether it's his code or someone else's I don't know, and it hardly matters). It's the kind of stuff we all do every day in Python, and despite the Zen of Python's advice that “there should be one, and preferably only one, obvious way to do it” there are many choices one could make that can impact the structure of the code.

This started out as a way to make the code more readable (I suspect it may have been written by somebody more accustomed to a language like C), but I thought it might be interesting to look at some timings as well.

In order to be able to run the code without providing various dependencies I have taken the liberty of defining a dummy Button function and various other “mock” objects to allow the code to run (they implement just enough to avoid exceptions being raised)*. This in turn means we can use IPython's %%timeit cell magic to determine whether my “improvements” actually help the execution speed.

Note that each timed cell is preceded by a garbage collection to try as far as possible to run the samples on a level playing field**.

In [1]:
import gc

class MockFrame():
def grid(self, row, column, sticky):
pass
mock_frame = MockFrame()

def Button(frame, text=None, fg=None, width=None, command=None, column=None, sticky=None):
return mock_frame

class Mock():
pass

self = Mock()
self.buttonRed, self.buttonBlue, self.buttonGreen, self.buttonBlack, self.buttonOpen = (None, )*5

f4 = Mock()
f4.columnconfigure = lambda c, weight: None

ALL = Mock()


The code in this next cell is extracted from the original code to avoid repetition - all loop implementations are written to use the same data.

In [2]:
button = ["Red", "Blue", "Green", "Black", "Open"]
color = ["red", "blue", "green", "black", "black"]
commands = [self.buttonRed, self.buttonBlue, self.buttonGreen,
self.buttonBlack, self.buttonOpen]


So here's the original piece of code:

In [3]:
g = gc.collect()

In [4]:
%%timeit
# Benchmark 1, the original code
for c in range(5):
f4.columnconfigure(c, weight=1)
Button(f4, text=button[c], fg=color[c], width=5,
command=commands[c]).grid(row=0, column=c, sticky=ALL)

100000 loops, best of 3: 4.45 µs per loop


You might suspect, as I did, that there are better ways to perform this loop.

The most obvious is simply to create a single list to iterate over, using unpacking assignment in the for loop to assign the individual elements to local variables. This certainly renders the loop body a little more readably. We do still need the column number, so we can use the enumerate() function to provide it.

In [5]:
g = gc.collect()

In [6]:
%%timeit
for c, (btn, col, cmd) in enumerate(zip(button, color, commands)):
f4.columnconfigure(c, weight=1)
Button(f4, text=btn, fg=col, width=5, command=cmd). \
grid(row=0, column=c, sticky=ALL)
pass

100000 loops, best of 3: 4.26 µs per loop


Unfortunately any speed advantage appears insignificant. These timings aren't very repeatable under the conditions I have run them, so really any difference is lost in the noise - what you see depends on the results when this notebook was run (and therefore also on which computer), and it would be unwise of me to make any predictions about the conditions under which you read it.

We can avoid the use of enumerate() by maintaining a loop counter, but from an esthetic point of view this is almost as bad (some would say worse) than iterating over the range of indices. In CPython it usually just comes out ahead, but at the cost of a certain amount of Pythonicity. It therefore makes the program a little less comprehensible.

In [7]:
g = gc.collect()

In [8]:
%%timeit
c = 0
for (btn, col, cmd) in zip(button, color, commands):
f4.columnconfigure(c, weight=1)
Button(f4, text=btn, fg=col, width=5, command=cmd). \
grid(row=0, column=c, sticky=ALL)
c += 1
pass

100000 loops, best of 3: 4.05 µs per loop


The next two cells repeat the same timings without the loop body, and this merely emphasises the speed gain of ditching the call to enumerate(). At this level of simplicity, though, it's difficult to tell how much optimization is taking place since the loop content is effectively null. I suspect PyPy would optimize this code out of existence. Who knows what CPython is actually measuring here.

In [9]:
g = gc.collect()

In [10]:
%%timeit
for c, (btn, col, cmd) in enumerate(zip(button, color, commands)):
pass

1000000 loops, best of 3: 1.18 µs per loop

In [11]:
g = gc.collect()

In [12]:
%%timeit
c = 0
for btn, col, cmd in zip(button, color, commands):
pass
c += 1

1000000 loops, best of 3: 854 ns per loop


Somewhat irritatingly, manual maintenance of an index variable appears to have a predictable slight edge over use of enumerate(), and naive programmers might therefore rush to convert all their code to this paradigm. Before they do so, though, they should consider that code's environment. In this particular example the whole piece of code is simply setup, executed once only at the start of the program execution as a GUI is being created. Optimization at this level woud not therefore be a sensible step: to optimize you should look first at the code inside the most deeply-nested and oft-executed loops.

If the timed code were to be executed billions of times inside two levels of nesting then one might, in production, consider using such an optimization if (and hopefully only if) there were a real need to extract every last ounce of speed from the hardware. In this case, since the program uses a graphical user interface and so user delays will use orders of magnitude more time than actual computing, it would be unwise to reduce the readability of the code, for which reason I prefer the enumerate()-based solution.

With many loops the body's processing time is likely to dominate in real cases, however, and that again supportus using enumerate(). If loop overhead accounts for 5% of each iteration and you reduce your loop control time by 30% you are still only reducing your total loop run time by 1.5%. So keep your program readable and Pythonically idiomatic.

Besides which, who knows, some Python dev might come along and change implementations to alter the relative time advantage, and then wouldn't you feel silly changing all that code back again?

* If you have a serious need for mock objects in testing, you really should look at the mock module, part of the standard library since Python 3.3. Thanks to Michael Foord for his valiant efforts. Please help him by not using mock in production.

** An interesting issue here. Originally I wrote the above code to create a new MockFrame object for each call to Button(), and I consistently saw the result of the second test as three orders of magnitude slower than the first (i.e. ms, not µs). It took me a while to understand why timeit was running so many iterations for such a long test, adding further to the elapsed time. It turned out the second test was paying the price of collecting the garbage from the first, and that without garbage collections in between runs the GC overhead would distort the timings.