Add a trace() and profile() utility

This commit is contained in:
Emi Simpson 2023-02-12 18:07:32 -05:00
parent d7dab8e4b0
commit 91ebe8d055
Signed by: Emi
GPG key ID: A12F2C2FFDC3D847

View file

@ -732,6 +732,44 @@ def sequence(s: Sequence[Result[A, B]]) -> Result[Sequence[A], B]:
assert isinstance(o, Err)
return o
def trace(x: A) -> A:
"""
Print a value in passing
Equivalent to the identity function **except** for the fact that it prints the value
to the screen before returning. The value is printed with the prefix "TRACE:" to make
it easy to see what printed.
>>> trace(1 + 2) * 4
TRACE: 3
12
"""
print(f'TRACE:', x)
return x
def profile(f: Callable[P, A]) -> Callable[P, A]:
"""
Wraps a function and check how long it takes to execute
Returns a function which is identical to the input, but when called, attempts to
record how long it takes to execute the function, and prints that information to the
screen.
>>> from time import sleep
>>> profile(ident)(1) #doctest: +ELLIPSIS
TIME OF ident(): ...ms
1
"""
from time import perf_counter
@wraps(f)
def profiled(*args: P.args, **kwargs: P.kwargs) -> A:
start_time = perf_counter()
o = f(*args, **kwargs)
stop_time = perf_counter()
print(f'TIME OF {f.__name__}(): {1000 * (stop_time - start_time):.2f}ms')
return o
return profiled
if __name__ == '__main__':
import doctest
doctest.testmod()