Add real time and process time timing functions
This commit is contained in:
1
__init__.py
Normal file
1
__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
import utils
|
||||
1
utils/__init__.py
Normal file
1
utils/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
import code
|
||||
67
utils/code.py
Normal file
67
utils/code.py
Normal 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
|
||||
Reference in New Issue
Block a user