Why is truth() faster than bool()? Part I
At TellApart, we use Python to code our real-time bidding server. Real-time bidding means we have to respond in a few milliseconds to requests from ad exchanges, or else we’re, well, out of business. So it’s critical that we know how to use all of our tools effectively.
There are faster languages than Python, but if you’re writing Python you can still speed things up without making anything less readable. Even where performance differences are small it pays to know what you’re doing. The knowledge may come in handy someday when you discover that an apparently simple piece of code has a disproportionate impact on execution time, perhaps only because it’s in a block that gets executed zillions of times.
With that introduction, here’s a survey of some tips we’ve assembled to write performant Python code on a line-by-line basis.
Today we’ll learn:
How to use timeit
Why you should prefer tuples instead of lists
Where and why you should use generator expressions instead of list expressions
The right way to instantiate a set()
Why not to use dict.keys()
1) Using timeit
The timeit module is the best way to evaluate the performance of small code snippets.
The most common way to use timeit:
timeit.Timer(“code to time”, “code to initialize”).timeit(number of times to run)
You can also use a lambda expression:
timeit.Timer(lambda: code to execute).timeit(number of times to run)
If you need to use a function from somewhere else you can import it in the “code to initialize” section; to import a function from the current context, you can do like so:
def foo():
...
timeit.Timer(“foo()”, “from __main__ import foo”).timeit(number of times to run)
We’re going to use timeit a lot in the examples below. Let’s get started.
2) Tuples are faster than lists
Use tuples instead of lists where possible, especially if you know you’re not going to modify it or you just need a dummy “empty list” object.
Here’s the difference between empty ones:
>>> timeit.Timer(
The Classifier