diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..c5fba9c --- /dev/null +++ b/__init__.py @@ -0,0 +1 @@ +import utils \ No newline at end of file diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000..92c2275 --- /dev/null +++ b/utils/__init__.py @@ -0,0 +1 @@ +import code \ No newline at end of file diff --git a/utils/code.py b/utils/code.py new file mode 100644 index 0000000..3e8b7d1 --- /dev/null +++ b/utils/code.py @@ -0,0 +1,67 @@ + +from typing import Callable, Any +from time import sleep, perf_counter, process_time + + +def time_real(func: Callable, *args, **kwargs) -> tuple[float, Any]: + """ + Measure the elapsed time for a given function in real time. + + Parameters + ---------- + func : Callable + The function to be measured. + *args : tuple + Positional arguments to be passed to the function. + **kwargs : dict + Keyword arguments to be passed to the function. + + Returns + ------- + tuple[float, Any] + A tuple containing the elapsed time in seconds and the return value of the function. + + Examples + -------- + >>> def my_func(x): + ... sleep(1) + ... return x ** 2 + >>> time_real(my_func, 5) + (1, 25) + """ + start = perf_counter() + ret = func(*args, **kwargs) + elapsed = perf_counter() - start + return elapsed, ret + + +def time_process(func: Callable, *args, **kwargs) -> tuple[float, Any]: + """ + Measure the elapsed time for a given function in CPU process time. + + Parameters + ---------- + func : Callable + The function to be measured. + *args : tuple + Positional arguments to be passed to the function. + **kwargs : dict + Keyword arguments to be passed to the function. + + Returns + ------- + tuple[float, Any] + A tuple containing the elapsed time in seconds and the return value of the function. + + Examples + -------- + >>> def my_func(x): + ... sleep(1) + ... return x ** 2 + >>> time_real(my_func, 5) + (0, 25) + """ + start = process_time() + ret = func(*args, **kwargs) + elapsed = process_time() - start + return elapsed, ret