PythonPerformancePresentation



PythonPerformancePresentation

0 0


PythonPerformancePresentation


On Github switowski / PythonPerformancePresentation

Benchmarks !

With: IPython and it's magic function %timeit

So let me show you some examples with benchmarks. The numbers are not important. What is important is how easily you can get some speed improvements.

#1 Count elements in list

# SLOW
how_many = 0
for element in BIG_LIST:
    how_many += 1
print how_many
# FAST
print len(BIG_LIST)

For 1 000 000 elements it's 26.5 ms vs 96.7 ns 274 000 times faster actually

Let's start with something simple. Let's say you want to count the number of elements in a list. You can easily write you own function with just a for loop that increments a variable. There is nothing wrong with this code, except that it's slow. You can achieve the same result using the built-in len() function. As you can see, the difference is quite huge. So, try to use the built-in functions when you can. There is just a few of them, so it's very easy to remember the most useful ones.
Note: Let say you want to check if an element belongs to a list. Most of you know that using this loop is not the best solution. You can instead use the index function together with some exception handling. It is faster and more pythonic because it is using one of the fundamental python rules: "ask for forgiveness, not for permission".