27 lines
665 B
Python
27 lines
665 B
Python
|
import time
|
||
|
from collections import defaultdict
|
||
|
from contextlib import ContextDecorator
|
||
|
from typing import Tuple
|
||
|
|
||
|
|
||
|
class Profiler(ContextDecorator):
|
||
|
results = defaultdict(float)
|
||
|
|
||
|
def __init__(self, name: str, excluded: Tuple = None) -> None:
|
||
|
self.name = name
|
||
|
self.excluded = excluded or ()
|
||
|
|
||
|
def __enter__(self):
|
||
|
self.start = time.time()
|
||
|
return self
|
||
|
|
||
|
def __exit__(self, *exc):
|
||
|
stop = time.time()
|
||
|
excluded = sum(self.results[e] for e in self.excluded)
|
||
|
self.results[self.name] += stop - self.start - excluded
|
||
|
return False
|
||
|
|
||
|
@classmethod
|
||
|
def reset(cls):
|
||
|
cls.results.clear()
|