Measure Execution Time of Python CodePython Python timeit Python time
In this article we’re going to learn how to calculate the execution time of your Python code with different approaches in Python.
For example, we need to test the speed of code snippet below:
total = 0.0 for i in range(1000000): total += i^2
Approach 1 - Using timeit module
With small code snippets we can use timeit module.
import timeit code_to_measure = """ total = 0.0 for i in range(1000000): total += i^2 """ elapsed_time = timeit.timeit(code_to_measure, number=1) print(elapsed_time)
Approach 2 - Using time module
With larger code snippets to measure, it is harder to input it as a string then you can use time as below example.
import time start_time = time.time() total = 0.0 for i in range(1000000): total += i^2 end_time = time.time() print(end_time - start_time)