Add a trace() and profile() utility
This commit is contained in:
parent
d7dab8e4b0
commit
91ebe8d055
|
@ -732,6 +732,44 @@ def sequence(s: Sequence[Result[A, B]]) -> Result[Sequence[A], B]:
|
||||||
assert isinstance(o, Err)
|
assert isinstance(o, Err)
|
||||||
return o
|
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__':
|
if __name__ == '__main__':
|
||||||
import doctest
|
import doctest
|
||||||
doctest.testmod()
|
doctest.testmod()
|
Loading…
Reference in a new issue