File: profiler.py

package info (click to toggle)
python-ptrace 0.9.9-0.3
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 808 kB
  • sloc: python: 10,167; ansic: 263; makefile: 164
file content (45 lines) | stat: -rw-r--r-- 1,232 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from profile import Profile
from os import unlink
from io import StringIO
import pstats


def calibrate(n):
    """
    https://docs.python.org/3/library/profile.html#calibration
    """
    if n > 0:
        pr = Profile()
        magics = []
        for i in range(n):
            magics.append(pr.calibrate(10000))
        return sum(magics) / n


def runProfiler(logger, func, args=tuple(), kw={},
                verbose=True, nb_func=25,
                sort_by=('time',), nb_cal=0):
    """
    Run a function in a profiler and then display the functions sorted by time.
    """
    profile_filename = "/tmp/profiler"
    prof = Profile(bias=calibrate(nb_cal))
    try:
        logger.warning("Run profiler")
        result = prof.runcall(func, *args, **kw)
        logger.error("Profiler: Process data...")
        prof.dump_stats(profile_filename)
        stat = pstats.Stats(prof)
        stat.strip_dirs()
        stat.sort_stats(*sort_by)

        logger.error("Profiler: Result:")
        log = StringIO()
        stat.stream = log
        stat.print_stats(nb_func)
        log.seek(0)
        for line in log:
            logger.error(line.rstrip())
        return result
    finally:
        unlink(profile_filename)