Source code for yyagl.engine.profiler

from os.path import exists


if not exists('main.pyo'):  # we don't deploy cProfile
    from cProfile import Profile
    from pstats import Stats
    from io import StringIO


[docs]class AbsProfiler(object):
[docs] @staticmethod def build(percall): prof_cls = AbsProfiler if not exists('main.pyo'): prof_cls = PerCallProfiler if percall else Profiler return prof_cls(percall)
def __init__(self, percall): pass
[docs] def printstats(self): pass
[docs] def toggle(self): pass
[docs] def destroy(self): pass
[docs]class Profiler(AbsProfiler): def __init__(self, percall): AbsProfiler.__init__(self, percall) self.percall = percall self.is_profiling = False # we can't infer from cProfile self.prof = Profile() self.stats = None
[docs] def toggle(self): if not self.is_profiling: self.__enable() else: self.__disable() self.printstats()
def __enable(self): self.prof.enable() self.is_profiling = True def __disable(self): self.prof.disable() self.is_profiling = False
[docs] def printstats(self): self.prof.disable() sio = StringIO() self.stats = Stats(self.prof, stream=sio).sort_stats('cumulative') self.stats.print_stats() self._print_lines(sio)
@staticmethod def _print_lines(sio): print(sio.getvalue())
[docs]class PerCallProfiler(Profiler): def _print_lines(self, sio): lines = sio.getvalue().split('\n') header_lines = lines[:5] content_lines = [line.split() for line in lines[5:] if line] sorted_lines = sorted(content_lines, key=lambda line: line[4]) sorted_lines = reversed(sorted_lines) # line[4] is the percall value joined_lines = ['\t'.join(line) for line in sorted_lines] print('\n'.join(header_lines + joined_lines))