Functional Programming
Calculating the runtime is one of the most common tasks in a Python script. Here is a decorator to handle this efficiently:
from functools import wraps
import time
def log_function_runtime(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"The {func.__name__} function took {end_time - start_time:.4f} seconds")
return result
return wrapper
Now calculating the function runtime by using this decorator:
import statistics
@log_function_runtime
def compute_stats(num_list):
mean = statistics.mean(num_list)
sd = statistics.stdev(num_list)
print(f'mean: {mean}, std: {sd}')
return mean, sd
compute_stats([1,2,3])
Visit GitHub: https://github.com/datanota/full-stack
Comments