Python code profiling in Debian

Sakis Kasampallis | May 8, 2011 min read
If you are coding in python, you are probably already familiar with the profiler concept. The problem is that the python profiler license fails to comply with the free software guidelines of Debian and therefore the package belongs to the non-free archive. "So what?", you might say. Well, personally I don't like to use software which belongs to the non-free archive both for philosophical and technical reasons. An important technical reason for instance is that Debian does not provide security updates for the non-free packages.

The next question is are there any alternative solutions? Thankfully the answer is yes. Since python 2.3 we can use the timeit module to test the efficiency of our code. Let me demonstrate the module using a simple example, taken from Downey's "Think Python" book (exception handling and the like are omitted for simplicity).


What we want to see here is how much more efficient is the recursive version of Fibonacci which uses a dictionary as a memo. Let's first see the result of the given code snippet (no memo version):
python3 fibo-timeit.py
113.601776838
Wow! It took almost 114 seconds the profiler to complete the test... Let's change the code to use the memo-based function:
t = Timer('fibonacci_ef(9)', 'from __main__ import fibonacci_ef')
So let's find out if memoization does indeed worth trying:
python3 fibo-timeit.py
1.40260386467
 
Hmmm.... Not bad. Happy Coding :)