Skip to content

Instantly share code, notes, and snippets.

@vovavili
Last active August 30, 2024 10:10
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
def time_function[**P, R](func: Callable[[P], R]) -> Callable[[P], R]:
"""
Time functions using a decorator.
Examples:
>>>import time
>>>
>>>@time_function
>>>def main() -> None:
>>> time.sleep(15)
>>>
>>>main()
20:58:28: Starting script...
The script took 15 seconds to run.
>>>@time_function
>>>def fn() -> None:
>>> time.sleep(61)
>>>
>>>fn()
22:47:29: Starting script...
Function "fn" took 1 minute and 1 second to run.
"""
@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_lst = [
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_lst)
if not t_len:
time_str = "less than a second"
elif t_len < 3:
time_str = " and ".join(time_lst)
else:
time_str = f"{time_lst[0]}, {' and '.join(time_lst[1:])}"
print(f"{f_name.capitalize()} took {time_str} to run.")
return result
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment