Debian Codegraph @

ptrace/profiler.py

raw
1 from profile import Profile
2 from os import unlink
3 from io import StringIO
4 import pstats
5
6
7 def calibrate(n):
8 """
9 https://docs.python.org/3/library/profile.html#calibration
10 """
11 if n > 0:
12 pr = Profile()
13 magics = []
14 for i in range(n):
15 magics.append(pr.calibrate(10000))
16 return sum(magics) / n
17
18
19 def runProfiler(logger, func, args=tuple(), kw={},
20 verbose=True, nb_func=25,
21 sort_by=('time',), nb_cal=0):
22 """
23 Run a function in a profiler and then display the functions sorted by time.
24 """
25 profile_filename = "/tmp/profiler"
26 prof = Profile(bias=calibrate(nb_cal))
27 try:
28 logger.warning("Run profiler")
29 result = prof.runcall(func, *args, **kw)
30 logger.error("Profiler: Process data...")
31 prof.dump_stats(profile_filename)
32 stat = pstats.Stats(prof)
33 stat.strip_dirs()
34 stat.sort_stats(*sort_by)
35
36 logger.error("Profiler: Result:")
37 log = StringIO()
38 stat.stream = log
39 stat.print_stats(nb_func)
40 log.seek(0)
41 for line in log:
42 logger.error(line.rstrip())
43 return result
44 finally:
45 unlink(profile_filename)