blob: 1184385ae1f1fe1909f59fc2d79619afcc51e6e4 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Armin Rigoa871ef22006-02-08 12:53:56 +00002
3"""Python interface for the 'lsprof' profiler.
4 Compatible with the 'profile' module.
5"""
6
Georg Brandlb6b13242009-09-04 17:15:16 +00007__all__ = ["run", "runctx", "Profile"]
Armin Rigoa871ef22006-02-08 12:53:56 +00008
9import _lsprof
Giampaolo Rodola'fca677a2013-02-25 11:36:40 +010010import profile as _pyprofile
Armin Rigoa871ef22006-02-08 12:53:56 +000011
12# ____________________________________________________________
13# Simple interface
14
15def run(statement, filename=None, sort=-1):
Giampaolo Rodola'fca677a2013-02-25 11:36:40 +010016 return _pyprofile._Utils(Profile).run(statement, filename, sort)
Armin Rigoa871ef22006-02-08 12:53:56 +000017
Georg Brandl8e43fbf2010-08-02 12:20:23 +000018def runctx(statement, globals, locals, filename=None, sort=-1):
Giampaolo Rodola'fca677a2013-02-25 11:36:40 +010019 return _pyprofile._Utils(Profile).runctx(statement, globals, locals,
20 filename, sort)
Armin Rigoa871ef22006-02-08 12:53:56 +000021
Giampaolo Rodola'fca677a2013-02-25 11:36:40 +010022run.__doc__ = _pyprofile.run.__doc__
23runctx.__doc__ = _pyprofile.runctx.__doc__
Armin Rigoa871ef22006-02-08 12:53:56 +000024
Armin Rigoa871ef22006-02-08 12:53:56 +000025# ____________________________________________________________
26
27class Profile(_lsprof.Profiler):
28 """Profile(custom_timer=None, time_unit=None, subcalls=True, builtins=True)
29
30 Builds a profiler object using the specified timer function.
31 The default timer is a fast built-in one based on real time.
32 For custom timer functions returning integers, time_unit can
33 be a float specifying a scale (i.e. how long each integer unit
34 is, in seconds).
35 """
36
37 # Most of the functionality is in the base class.
38 # This subclass only adds convenient and backward-compatible methods.
39
40 def print_stats(self, sort=-1):
41 import pstats
42 pstats.Stats(self).strip_dirs().sort_stats(sort).print_stats()
43
44 def dump_stats(self, file):
45 import marshal
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +010046 with open(file, 'wb') as f:
47 self.create_stats()
48 marshal.dump(self.stats, f)
Armin Rigoa871ef22006-02-08 12:53:56 +000049
50 def create_stats(self):
51 self.disable()
52 self.snapshot_stats()
53
54 def snapshot_stats(self):
55 entries = self.getstats()
56 self.stats = {}
57 callersdicts = {}
58 # call information
59 for entry in entries:
60 func = label(entry.code)
61 nc = entry.callcount # ncalls column of pstats (before '/')
62 cc = nc - entry.reccallcount # ncalls column of pstats (after '/')
63 tt = entry.inlinetime # tottime column of pstats
64 ct = entry.totaltime # cumtime column of pstats
65 callers = {}
66 callersdicts[id(entry.code)] = callers
67 self.stats[func] = cc, nc, tt, ct, callers
68 # subcall information
69 for entry in entries:
70 if entry.calls:
71 func = label(entry.code)
72 for subentry in entry.calls:
73 try:
74 callers = callersdicts[id(subentry.code)]
75 except KeyError:
76 continue
77 nc = subentry.callcount
78 cc = nc - subentry.reccallcount
79 tt = subentry.inlinetime
80 ct = subentry.totaltime
81 if func in callers:
82 prev = callers[func]
83 nc += prev[0]
84 cc += prev[1]
85 tt += prev[2]
86 ct += prev[3]
87 callers[func] = nc, cc, tt, ct
88
89 # The following two methods can be called by clients to use
90 # a profiler to profile a statement, given as a string.
91
92 def run(self, cmd):
93 import __main__
94 dict = __main__.__dict__
95 return self.runctx(cmd, dict, dict)
96
97 def runctx(self, cmd, globals, locals):
98 self.enable()
99 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +0000100 exec(cmd, globals, locals)
Armin Rigoa871ef22006-02-08 12:53:56 +0000101 finally:
102 self.disable()
103 return self
104
105 # This method is more useful to profile a single function call.
106 def runcall(self, func, *args, **kw):
107 self.enable()
108 try:
109 return func(*args, **kw)
110 finally:
111 self.disable()
112
113# ____________________________________________________________
114
115def label(code):
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000116 if isinstance(code, str):
Armin Rigoa871ef22006-02-08 12:53:56 +0000117 return ('~', 0, code) # built-in functions ('~' sorts at the end)
118 else:
119 return (code.co_filename, code.co_firstlineno, code.co_name)
120
121# ____________________________________________________________
122
123def main():
124 import os, sys
125 from optparse import OptionParser
126 usage = "cProfile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
127 parser = OptionParser(usage=usage)
128 parser.allow_interspersed_args = False
129 parser.add_option('-o', '--outfile', dest="outfile",
130 help="Save stats to <outfile>", default=None)
131 parser.add_option('-s', '--sort', dest="sort",
Georg Brandl8e43fbf2010-08-02 12:20:23 +0000132 help="Sort order when printing to stdout, based on pstats.Stats class",
133 default=-1)
Armin Rigoa871ef22006-02-08 12:53:56 +0000134
135 if not sys.argv[1:]:
136 parser.print_usage()
137 sys.exit(2)
138
139 (options, args) = parser.parse_args()
140 sys.argv[:] = args
141
Georg Brandl8e43fbf2010-08-02 12:20:23 +0000142 if len(args) > 0:
143 progname = args[0]
144 sys.path.insert(0, os.path.dirname(progname))
145 with open(progname, 'rb') as fp:
146 code = compile(fp.read(), progname, 'exec')
147 globs = {
148 '__file__': progname,
149 '__name__': '__main__',
150 '__package__': None,
151 '__cached__': None,
152 }
153 runctx(code, globs, None, options.outfile, options.sort)
Armin Rigoa871ef22006-02-08 12:53:56 +0000154 else:
155 parser.print_usage()
156 return parser
157
158# When invoked as main program, invoke the profiler on a script
159if __name__ == '__main__':
160 main()