Skip to content

Instantly share code, notes, and snippets.

@oidualc
Last active August 11, 2022 10:07
Show Gist options
  • Save oidualc/0d2461d23c5d48aca9783266db685d88 to your computer and use it in GitHub Desktop.
Save oidualc/0d2461d23c5d48aca9783266db685d88 to your computer and use it in GitHub Desktop.
Timer functions Python
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