-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathprofiler.py
43 lines (37 loc) · 1.19 KB
/
profiler.py
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
33
34
35
36
37
38
39
40
41
42
43
from functools import wraps
import tracemalloc
import time
def profile(f):
"""
## Decorator to profile memory usage by a function
"""
def memory_humanize(num, suffix="B"):
"""
## Convert bytes to human readable format
"""
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if abs(num) < 1024.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1024.0
return f"{num:.1f}Yi{suffix}"
def time_humanize(seconds):
"""
## Convert seconds to human readable format
"""
h = int(seconds / 3600)
m = int((seconds % 3600) / 60)
s = int(seconds % 60)
return f"{h}h {m}m {s}s"
@wraps(f)
def decorator(*args, **kwargs):
tracemalloc.start()
start_time = time.time()
res = f(*args, **kwargs)
current, peak = tracemalloc.get_traced_memory()
print(f"profiler.mem.current: {memory_humanize(current) }")
print(f"profiler.mem.peak: {memory_humanize(peak) }")
tracemalloc.stop()
end_time = time.time()
print(f"profiler.duration: {time_humanize(end_time-start_time)}")
return res
return decorator