| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
import os |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
if not int(os.environ.get('MLAT_CPU_PROFILE', '0')): |
| 25 |
def trackcpu(f, **kwargs): |
| 26 |
return f |
| 27 |
|
| 28 |
def dump_cpu_profiles(): |
| 29 |
pass |
| 30 |
else: |
| 31 |
import sys |
| 32 |
import time |
| 33 |
import operator |
| 34 |
import functools |
| 35 |
|
| 36 |
_cpu_tracking = [] |
| 37 |
print('CPU profiling enabled', file=sys.stderr) |
| 38 |
|
| 39 |
def trackcpu(f, name=None, **kwargs): |
| 40 |
if name is None: |
| 41 |
name = f.__module__ + '.' + f.__qualname__ |
| 42 |
|
| 43 |
print('Profiling:', name, file=sys.stderr) |
| 44 |
tracking = [name, 0, 0.0] |
| 45 |
_cpu_tracking.append(tracking) |
| 46 |
|
| 47 |
@functools.wraps(f) |
| 48 |
def cpu_measurement_wrapper(*args, **kwargs): |
| 49 |
start = time.clock_gettime(time.CLOCK_THREAD_CPUTIME_ID) |
| 50 |
try: |
| 51 |
return f(*args, **kwargs) |
| 52 |
finally: |
| 53 |
end = time.clock_gettime(time.CLOCK_THREAD_CPUTIME_ID) |
| 54 |
tracking[1] += 1 |
| 55 |
tracking[2] += (end - start) |
| 56 |
|
| 57 |
return cpu_measurement_wrapper |
| 58 |
|
| 59 |
def dump_cpu_profiles(): |
| 60 |
print('{rank:4s} {name:60s} {count:6s} {total:8s} {each:8s}'.format( |
| 61 |
rank='#', |
| 62 |
name='Function', |
| 63 |
count='Calls', |
| 64 |
total='Total(s)', |
| 65 |
each='Each(us)'), file=sys.stderr) |
| 66 |
|
| 67 |
rank = 1 |
| 68 |
for name, count, total in sorted(_cpu_tracking, key=operator.itemgetter(2), reverse=True): |
| 69 |
if count == 0: |
| 70 |
break |
| 71 |
|
| 72 |
print('{rank:4d} {name:60s} {count:6d} {total:8.3f} {each:8.0f}'.format( |
| 73 |
rank=rank, |
| 74 |
name=name, |
| 75 |
count=count, |
| 76 |
total=total, |
| 77 |
each=total * 1e6 / count), file=sys.stderr) |
| 78 |
rank += 1 |
| 79 |
|
| 80 |
sys.stderr.flush() |