File: profiler.py

package info (click to toggle)
python-ptrace 0.6.4-2
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 620 kB
  • sloc: python: 6,213; ansic: 241; makefile: 13; sh: 1
file content (36 lines) | stat: -rw-r--r-- 1,011 bytes parent folder | download | duplicates (2)
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
from hotshot import Profile
from hotshot.stats import load as loadStats
from os import unlink
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

def runProfiler(logger, func, args=tuple(), kw={},
verbose=True, nb_func=25,
sort_by=('time',)):
    """
    Run a function in a profiler and then display the functions sorted by time.
    """
    profile_filename = "/tmp/profiler"
    prof = Profile(profile_filename)
    try:
        logger.warning("Run profiler")
        result = prof.runcall(func, *args, **kw)
        prof.close()
        logger.error("Profiler: Process data...")
        stat = loadStats(profile_filename)
        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)