Debian Codegraph @

mlat/profile.py

raw symbols SCIP
1 # -*- mode: python; indent-tabs-mode: nil -*-
2
3 # Part of mlat-client - an ADS-B multilateration client.
4 # Copyright 2015, Oliver Jowett <[email protected]>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 import os
20
21 # NB: This requires Python 3.3 when MLAT_CPU_PROFILE is set.
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()