Skip to content

Instantly share code, notes, and snippets.

@vovavili
Last active June 11, 2024 08:16
Show Gist options
  • Save vovavili/5e3b7ebad52f5b29a5eba9b9d68f2139 to your computer and use it in GitHub Desktop.
Save vovavili/5e3b7ebad52f5b29a5eba9b9d68f2139 to your computer and use it in GitHub Desktop.
Time Python scripts
"""Time functions using a decorator."""
import time
from collections.abc import Callable
from functools import wraps
from typing import ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def time_function(func: Callable[P, R]) -> Callable[P, R]:
"""Time functions using a decorator."""
@wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
starting_time = time.perf_counter()
f_name = func.__name__
f_name = "main function" if f_name == "main" else f'function "{f_name}"'
print(f"{time.strftime('%H:%M:%S', time.localtime())}: Starting {f_name}...")
result = func(*args, **kwargs)
elapsed_time = time.perf_counter() - starting_time
hours, remainder = divmod(int(elapsed_time), 3600)
minutes, seconds = divmod(remainder, 60)
time_str = [
f"{n} {unit if n == 1 else unit + 's'}"
for n, unit in ((hours, "hour"), (minutes, "minute"), (seconds, "second"))
if n
]
t_len = len(time_str)
if not t_len:
time_str = "less than a second"
elif t_len < 3:
time_str = " and ".join(time_str)
else:
time_str = f"{time_str[0]}, {' and '.join(time_str[1:])}"
print(f"{f_name} took {time_str} to run.".capitalize())
return result
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment