To measure the execution time of a Python program, you can use several methods depending on your needs. Here are the most common approaches:
1. Using time.time()
(Simple Wall-Clock Time)
This method measures the total elapsed time (wall-clock time) between two points in your code.
import time
start_time = time.time()
# Your code here
for _ in range(1000000):
pass
end_time = time.time()
execution_time = end_time - start_time
print(f"Execution time: {execution_time:.4f} seconds")
Pros: Simple and easy to use.
Cons: Includes time from other processes running on the system.
2. Using time.perf_counter()
(High Precision)
Provides a higher-resolution timer for benchmarking code performance.
import time
start = time.perf_counter()
# Your code here
result = sum(range(1000000))
end = time.perf_counter()
print(f"Time taken: {end - start:.6f} seconds")
Pros: More precise than time.time()
.
Cons: Still measures wall-clock time.
3. Using the timeit
Module (For Code Snippets)
Ideal for timing small code snippets and averaging multiple runs.
Command Line:
python -m timeit -n 1000 -r 5 "your_code_here"
-n
: Number of loops per run.-r
: Number of repetitions.
Within Python:
import timeit
code_to_test = """
result = sum(range(1000000))
"""
execution_time = timeit.timeit(code_to_test, number=1000)
print(f"Average time: {execution_time / 1000:.6f} seconds")
Pros: Runs code multiple times for accuracy.
Cons: Requires code to be a string or callable.
4. Using a Context Manager (Reusable)
Create a reusable timer for cleaner code:
import time
from contextlib import contextmanager
@contextmanager
def timer():
start = time.perf_counter()
yield
end = time.perf_counter()
print(f"Time: {end - start:.4f} sec")
# Usage
with timer():
# Code to time
sum(range(1000000))
5. Using datetime
(Human-Readable Output)
For a formatted time output (e.g., hours:minutes:seconds):
from datetime import datetime
start = datetime.now()
# Your code here
sum(range(1000000))
end = datetime.now()
print(f"Time: {end - start}")
6. Profiling Entire Scripts with cProfile
For detailed profiling (not just total time):
python -m cProfile your_script.py
Which Method Should You Use?
Use Case | Recommended Method |
---|---|
Simple timing | time.time() |
High-precision benchmarks | time.perf_counter() |
Small code snippets | timeit module |
Reusable timing | Context manager |
Detailed performance stats | cProfile |
Example: Full Program Timing
import time
def main():
# Your program logic here
total = 0
for i in range(1000000):
total += i
print("Sum:", total)
if __name__ == "__main__":
start = time.perf_counter()
main()
end = time.perf_counter()
print(f"Total execution time: {end - start:.4f} seconds")
Output:
Sum: 499999500000
Total execution time: 0.0453 seconds
Key Notes
- Short-running code: Use
timeit
for reliable averages. - Real-world timing:
time.perf_counter()
minimizes system interference. - Avoid
time.sleep()
: It can skew results if used in your code.