Python: Measure the execution time of small python code

The “timeit” module lets you measure the execution time of small bits of Python code. This can help you find the execution time of your code and thus help in a quick performance improvement of your code. A tiny example follows.

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

0.2938678440004878

>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)

0.26015590599854477

>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)

0.26461737899808213

Please note that every time, the execution time varies for the same snippet. in the first two cases. The third one does the same thing but has a different execution time. This profiling helps with performant code going to your production.

Also, this different execution time for the same exact code depends on a lot of factors, the major one being how busy your CPU was at the time of executing this code. The module function timeit.timeit(stmt, setup, timer, number) accepts four arguments:

  • stmt which is the statement you want to measure; it defaults to ‘pass’.
  • setup which is the code that you run before running the stmt; it defaults to ‘pass’.
    We generally use this to import the required modules for our code.
  • timer which is a timeit.Timer object; it usually has a sensible default value so you don’t have to worry about it.
  • number which is the number of executions you’d like to run the stmt.

https://docs.python.org/2/library/timeit.html
https://www.geeksforgeeks.org/timeit-python-examples/

Leave a Reply

Your email address will not be published. Required fields are marked *