contextlib.ContextDecorator
를 이용하여 간단하고 유용한 timer를 만들 수 있다.
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
from dataclasses import dataclass
from contextlib import ContextDecorator
from time import time
@dataclass
class Timer(ContextDecorator):
id: int = 0
def __enter__(self):
print(); print("="*50)
self.start_time = time()
return self
def __exit__(self, *exc):
elapsed_time = time() - self.start_time
print("=" * 50)
print(f"[Elapsed time] Timer {self.id}: {elapsed_time:.2f}s ({elapsed_time:.2f}m)")
return False
@Timer()
def print_hello():
print("Hello, world!")
if __name__ == "__main__":
print_hello()
with Timer(1):
print("Do something...")
==================================================
Hello, world!
==================================================
[Elapsed time] Timer 0: 0.00s (0.00m)
==================================================
Do something...
==================================================
[Elapsed time] Timer 1: 0.00s (0.00m)
PREVIOUSEtc