How to Measure Execution Time in Python Quickly and Easily
time module by recording the start and end times with time.time(). For more precise timing, use the timeit module which runs code multiple times and gives an average duration.Syntax
To measure execution time with the time module, you record the start time before the code runs and the end time after it finishes. The difference gives the elapsed time.
Using timeit, you pass the code as a string or function to run it multiple times and get an average execution time.
import time start = time.time() # code to measure end = time.time() elapsed = end - start import timeit elapsed_time = timeit.timeit('code_to_test()', number=1000)
Example
This example shows how to measure the time taken to sum numbers from 1 to 1 million using both time and timeit modules.
import time import timeit def sum_numbers(): return sum(range(1, 1000001)) # Using time module start = time.time() sum_numbers() end = time.time() print(f"Elapsed time using time module: {end - start:.6f} seconds") # Using timeit module elapsed = timeit.timeit(sum_numbers, number=10) print(f"Average time using timeit module over 10 runs: {elapsed / 10:.6f} seconds")
Common Pitfalls
One common mistake is measuring time with time.time() for very fast code, which can be inaccurate due to low resolution. Also, running the code only once may give misleading results because of background processes affecting timing.
Using timeit avoids these issues by running the code multiple times and providing a more reliable average.
import time start = time.time() for i in range(1000): pass end = time.time() print(f"Elapsed time (single run): {end - start} seconds") import timeit elapsed = timeit.timeit('for i in range(1000): pass', number=1000) print(f"Elapsed time (1000 runs): {elapsed} seconds")
Quick Reference
Here is a quick summary of methods to measure execution time in Python:
| Method | Usage | Best For |
|---|---|---|
| time.time() | Record start and end time around code | Simple timing for longer tasks |
| time.perf_counter() | High resolution timer for start/end | More precise timing than time.time() |
| timeit.timeit() | Run code multiple times and average | Accurate timing for small or fast code snippets |