Python Measure Execution Time
Sometimes it is nice to get a feeling for the execution time of certain code snippets in Python, especially if you want to find bottlenecks and optimize your code.
There are several ways to measure the execution time and in this article, I will show you some of them.
Simple and Quick
import time start = time.time() # do something end = time.time() print('That took ' + str(end-start) + ' seconds')
The library timeit is meant for developers to measure execution time for optimization purposes. It is a built-in library and has some advanced features, for example to repeat code snippets and measure average or minimal execution times.
import timeit def yourfunction(x): return x * x print(timeit.repeat("for x in range(10): yourfunction(x)", "from __main__ import yourfunction", number=100))