Python : Profiling / timing your code

A good code not only gives expected results but also performs better (i.e takes less time ).

Sometimes its important to know how long your code is taking to run, or at least know if a particular line of code is slowing down your entire project. Python has a built-in timing module to do this.

This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.

Lets learn about timeit!

We’ll pass two arguments the actual line we want to test encapsulated as a string and the number of times we wish to run it. Here we’ll choose 10,000 runs to get some high enough numbers to comapre various methods.

import timeit

# For loop
time_to_execute = timeit.timeit(‘”-“.join(str(n) for n in range(100))’, number=10000)
print time_to_execute

# List comprehension
time_to_execute = timeit.timeit(‘”-“.join([str(n) for n in range(100)])’, number=10000)
print time_to_execute

# Map()
time_to_execute = timeit.timeit(‘”-“.join(map(str, range(100)))’, number=10000)
print time_to_execute

 

$$$$$  Output $$$$$$$$$
/usr/bin/python /Users/asee2278/gitRepo/petProjects/pythonPlayground/oop/Debugger.py

0.225734949112
0.197602033615
0.122097969055

We observed that all blocks of code were doing exact same thing, but map() wins over other in terms of performance.

Advertisements