Compare commits

1 Commits

Author SHA1 Message Date
911a6c6f06 Add real time and process time timing functions 2024-10-30 10:38:29 +01:00
3 changed files with 69 additions and 0 deletions

1
__init__.py Normal file
View File

@@ -0,0 +1 @@
import utils

1
utils/__init__.py Normal file
View File

@@ -0,0 +1 @@
import code

67
utils/code.py Normal file
View File

@@ -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