Last active
August 11, 2022 10:07
-
-
Save oidualc/0d2461d23c5d48aca9783266db685d88 to your computer and use it in GitHub Desktop.
Timer functions Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import perf_counter | |
from typing import Any, Callable, Coroutine, ParamSpec, TypeVar | |
T = TypeVar("T") | |
P = ParamSpec("P") | |
def with_timer(fn: Callable[P, T]) -> Callable[P, T]: | |
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: | |
t0 = perf_counter() | |
result = fn(*args, **kwargs) | |
print( | |
f"Executed {fn.__name__} {args} {kwargs} in {perf_counter() - t0:.2f}s" | |
) | |
return result | |
return wrapper | |
def with_timer_async( | |
fn: Callable[P, Coroutine[Any, Any, T]] | |
) -> Callable[P, Coroutine[Any, Any, T]]: | |
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: | |
t0 = perf_counter() | |
result = await fn(*args, **kwargs) | |
print( | |
f"Executed {fn.__name__} {args} {kwargs} in {perf_counter() - t0:.2f}s" | |
) | |
return result | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment