Here are a few ways to measure time elapsed in a function using decorators in Python:
- Simple decorator using time.time():
import time
from functools import wraps
def measure_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time:.4f} seconds to execute")
return result
return wrapper
# Usage example:
@measure_time
def my_function(n):
time.sleep(n) # Simulate some work
return n
my_function(2) # Output: my_function took 2.0021 seconds to execute
- More detailed decorator using time.perf_counter() (more precise):
import time
from functools import wraps
def measure_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(f"Function: {func.__name__}")
print(f"Time elapsed: {elapsed_time:.4f} seconds")
return result
return wrapper
@measure_time
def example_function():
time.sleep(1)
return "Done"
- Decorator with statistics for multiple calls:
import time
from functools import wraps
from statistics import mean, stdev
def measure_time_stats(num_runs=1):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
times = []
results = None
for _ in range(num_runs):
start_time = time.perf_counter()
results = func(*args, **kwargs)
end_time = time.perf_counter()
times.append(end_time - start_time)
print(f"\nFunction: {func.__name__}")
print(f"Number of runs: {num_runs}")
print(f"Average time: {mean(times):.4f} seconds")
if num_runs > 1:
print(f"Std dev: {stdev(times):.4f} seconds")
print(f"Min time: {min(times):.4f} seconds")
print(f"Max time: {max(times):.4f} seconds")
return results
return wrapper
return decorator
# Usage example:
@measure_time_stats(num_runs=5)
def complex_calculation(n):
time.sleep(n)
return n
complex_calculation(1)
- Context manager version (not a decorator but useful alternative):
import time
from contextlib import contextmanager
@contextmanager
def measure_time_block(name="Block"):
start_time = time.perf_counter()
yield
end_time = time.perf_counter()
print(f"{name} took {end_time - start_time:.4f} seconds")
# Usage example:
with measure_time_block("My calculation"):
time.sleep(1)
- Decorator with logging:
import time
import logging
from functools import wraps
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def measure_time_logged(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
elapsed_time = end_time - start_time
logger.info(f"{func.__name__} took {elapsed_time:.4f} seconds to execute")
return result
return wrapper
@measure_time_logged
def sample_function():
time.sleep(1)
return "Done"
Key points to remember:
- Always use
@wraps(func) from functools to preserve the original function's metadata.
time.perf_counter() is more precise than time.time() for timing measurements.
- For more accurate measurements of very fast functions, you might want to run multiple times and take statistics.
- Consider using logging instead of print statements in production code.
- The context manager version can be useful when you want to measure specific blocks of code rather than entire functions.
Choose the version that best fits your needs based on:
- Whether you need simple timing or detailed statistics
- Whether you want logging or print statements
- How precise the measurements need to be
- Whether you want to measure multiple runs