-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminitime.py
More file actions
32 lines (28 loc) · 993 Bytes
/
Copy pathminitime.py
File metadata and controls
32 lines (28 loc) · 993 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import time
from contextlib import contextmanager
from typing import Callable
def minitime(f: Callable):
"""Time a function, prints the time in nanosecond. Example: @minitime
Args:
f (Callable): The underlying function that decorator wraps
"""
def time_func(*args, **kwargs):
ts = time.perf_counter_ns()
result = f(*args, **kwargs)
te = time.perf_counter_ns()
formatted = [a for a in args]
formatted.extend([f'{k}={v}' for k, v in kwargs.items()])
print(f'{f.__name__}({",".join(map(str, formatted))}) took {te - ts}ns')
return result
return time_func
@contextmanager
def minitime_context(name: str):
"""Time a block of code, prints the time in nanosecond. Example: with minitime_context("snippet_1")
Args:
name (str): the name of the code block
"""
ts = time.perf_counter_ns()
try:
yield
finally:
print(f'Code[{name}] took {time.perf_counter_ns() - ts}ns')