To measure elapsed time in Python, you can use the time
module, which provides several high-resolution timers. Here’s a concise guide:
1. Basic Elapsed Time (Wall-Clock)
Use time.perf_counter()
for precise measurements:
import time
start = time.perf_counter()
# Your code here
end = time.perf_counter()
elapsed = end - start
print(f"Elapsed time: {elapsed:.6f} seconds")
2. Reusable Context Manager
Encapsulate timing logic for cleaner code:
from contextlib import contextmanager
import time
@contextmanager
def timer():
start = time.perf_counter()
yield
end = time.perf_counter()
print(f"Time: {end - start:.6f} seconds")
# Usage:
with timer():
# Code to time
time.sleep(1)
3. CPU Time (Process Time)
Measure CPU time (ignoring sleep/wait time):
start = time.process_time()
# Code here
end = time.process_time()
print(f"CPU Time: {end - start:.6f} seconds")
4. Using timeit
for Small Code Snippets
Benchmark code with the timeit
module:
import timeit
code_to_test = """
result = sum(range(1000))
"""
time_taken = timeit.timeit(code_to_test, number=1000)
print(f"Time per loop: {time_taken / 1000:.6f} seconds")
Key Functions Comparison
Function | Use Case |
---|---|
time.perf_counter() | High-resolution wall-clock timing (best for most cases). |
time.process_time() | CPU time (excludes sleep/system calls). |
time.time() | Simple wall-clock time (less precise). |
timeit.timeit() | Benchmark small code snippets with loops. |
Example: Decorator for Function Timing
import time
def time_decorator(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.__name__} took {end - start:.6f} seconds")
return result
return wrapper
@time_decorator
def my_function():
time.sleep(2)
my_function() # Output: "my_function took 2.000456 seconds"
Notes
- Precision:
perf_counter()
is monotonic and ideal for benchmarking. - Avoid
time.time()
for short intervals due to lower resolution. - Jupyter/IPython: Use
%timeit
magic command for quick snippets.
Choose the method that best fits your use case!