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/


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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.