diff --git a/emis_funky_funktions.py b/emis_funky_funktions.py index 802b522..968ed84 100644 --- a/emis_funky_funktions.py +++ b/emis_funky_funktions.py @@ -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() \ No newline at end of file