1 from os
.path
import exists
4 if not exists('main.pyo'): # we don't deploy cProfile
5 from cProfile
import Profile
6 from pstats
import Stats
7 from io
import StringIO
14 prof_cls
= AbsProfiler
15 if not exists('main.pyo'):
16 prof_cls
= PerCallProfiler
if percall
else Profiler
17 return prof_cls(percall
)
19 def __init__(self
, percall
): pass
21 def printstats(self
): pass
23 def toggle(self
): pass
25 def destroy(self
): pass
28 class Profiler(AbsProfiler
):
30 def __init__(self
, percall
):
31 AbsProfiler
.__init
__(self
, percall
)
32 self
.percall
= percall
33 self
.is_profiling
= False # we can't infer from cProfile
38 if not self
.is_profiling
: self
.__enable
()
45 self
.is_profiling
= True
49 self
.is_profiling
= False
54 self
.stats
= Stats(self
.prof
, stream
=sio
).sort_stats('cumulative')
55 self
.stats
.print_stats()
56 self
._print
_lines
(sio
)
59 def _print_lines(sio
): print(sio
.getvalue())
62 class PerCallProfiler(Profiler
):
64 def _print_lines(self
, sio
):
65 lines
= sio
.getvalue().split('\n')
66 header_lines
= lines
[:5]
67 content_lines
= [line
.split() for line
in lines
[5:] if line
]
68 sorted_lines
= sorted(content_lines
, key
=lambda line
: line
[4])
69 sorted_lines
= reversed(sorted_lines
)
70 # line[4] is the percall value
71 joined_lines
= ['\t'.join(line
) for line
in sorted_lines
]
72 print('\n'.join(header_lines
+ joined_lines
))