blob: b92bd91882539ff6d0265ae6218e9cc05fad4d5d [file] [log] [blame]
Guido van Rossumf06ee5f1996-11-27 19:52:01 +00001#! /usr/bin/env python
Guido van Rossum81762581992-04-21 15:36:23 +00002#
Guido van Rossumb6775db1994-08-01 11:34:53 +00003# Class for profiling python code. rev 1.0 6/2/94
Guido van Rossum81762581992-04-21 15:36:23 +00004#
Guido van Rossumb6775db1994-08-01 11:34:53 +00005# Based on prior profile module by Sjoerd Mullender...
6# which was hacked somewhat by: Guido van Rossum
7#
8# See profile.doc for more information
9
Guido van Rossum54f22ed2000-02-04 15:10:34 +000010"""Class for profiling Python code."""
Guido van Rossumb6775db1994-08-01 11:34:53 +000011
12# Copyright 1994, by InfoSeek Corporation, all rights reserved.
13# Written by James Roskind
Tim Peters2344fae2001-01-15 00:50:52 +000014#
Guido van Rossumb6775db1994-08-01 11:34:53 +000015# Permission to use, copy, modify, and distribute this Python software
16# and its associated documentation for any purpose (subject to the
17# restriction in the following sentence) without fee is hereby granted,
18# provided that the above copyright notice appears in all copies, and
19# that both that copyright notice and this permission notice appear in
20# supporting documentation, and that the name of InfoSeek not be used in
21# advertising or publicity pertaining to distribution of the software
22# without specific, written prior permission. This permission is
23# explicitly restricted to the copying and modification of the software
24# to remain in Python, compiled Python, or other languages (such as C)
25# wherein the modified or derived code is exclusively imported into a
26# Python module.
Tim Peters2344fae2001-01-15 00:50:52 +000027#
Guido van Rossumb6775db1994-08-01 11:34:53 +000028# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
29# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
30# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
31# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
32# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
33# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
34# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35
36
Guido van Rossum81762581992-04-21 15:36:23 +000037
38import sys
Guido van Rossum4e160981992-09-02 20:43:20 +000039import os
Guido van Rossumb6775db1994-08-01 11:34:53 +000040import time
Guido van Rossum4e160981992-09-02 20:43:20 +000041import marshal
Guido van Rossum81762581992-04-21 15:36:23 +000042
Skip Montanaroc62c81e2001-02-12 02:00:42 +000043__all__ = ["run","help","Profile"]
Guido van Rossum81762581992-04-21 15:36:23 +000044
Tim Peters2344fae2001-01-15 00:50:52 +000045# Sample timer for use with
Guido van Rossumb6775db1994-08-01 11:34:53 +000046#i_count = 0
47#def integer_timer():
Tim Peters2344fae2001-01-15 00:50:52 +000048# global i_count
49# i_count = i_count + 1
50# return i_count
Guido van Rossumb6775db1994-08-01 11:34:53 +000051#itimes = integer_timer # replace with C coded timer returning integers
Guido van Rossum81762581992-04-21 15:36:23 +000052
Guido van Rossumb6775db1994-08-01 11:34:53 +000053#**************************************************************************
54# The following are the static member functions for the profiler class
55# Note that an instance of Profile() is *not* needed to call them.
56#**************************************************************************
Guido van Rossum81762581992-04-21 15:36:23 +000057
Jeremy Hyltonadcf8a02001-03-14 20:01:19 +000058def run(statement, filename=None):
59 """Run statement under profiler optionally saving results in filename
Guido van Rossum4e160981992-09-02 20:43:20 +000060
Jeremy Hyltonadcf8a02001-03-14 20:01:19 +000061 This function takes a single argument that can be passed to the
62 "exec" statement, and an optional file name. In all cases this
63 routine attempts to "exec" its first argument and gather profiling
64 statistics from the execution. If no file name is present, then this
65 function automatically prints a simple profiling report, sorted by the
66 standard name string (file/line/function-name) that is presented in
67 each line.
68 """
Tim Peters2344fae2001-01-15 00:50:52 +000069 prof = Profile()
70 try:
71 prof = prof.run(statement)
72 except SystemExit:
73 pass
Jeremy Hyltonadcf8a02001-03-14 20:01:19 +000074 if filename is not None:
75 prof.dump_stats(filename)
Tim Peters2344fae2001-01-15 00:50:52 +000076 else:
77 return prof.print_stats()
Guido van Rossume61fa0a1993-10-22 13:56:35 +000078
79# print help
80def help():
Tim Peters2344fae2001-01-15 00:50:52 +000081 for dirname in sys.path:
82 fullname = os.path.join(dirname, 'profile.doc')
83 if os.path.exists(fullname):
84 sts = os.system('${PAGER-more} '+fullname)
85 if sts: print '*** Pager exit status:', sts
86 break
87 else:
88 print 'Sorry, can\'t find the help file "profile.doc"',
89 print 'along the Python search path'
Guido van Rossumb6775db1994-08-01 11:34:53 +000090
91
Fred Drakeedb5ffb2001-06-08 04:25:24 +000092if os.name == "mac":
Jack Jansen1bdcadd2001-06-19 20:11:36 +000093 import MacOS
Fred Drakeedb5ffb2001-06-08 04:25:24 +000094 def _get_time_mac(timer=MacOS.GetTicks):
95 return timer() / 60.0
96
97if hasattr(os, "times"):
98 def _get_time_times(timer=os.times):
99 t = timer()
100 return t[0] + t[1]
101
102
Guido van Rossumb6775db1994-08-01 11:34:53 +0000103class Profile:
Tim Peters2344fae2001-01-15 00:50:52 +0000104 """Profiler class.
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000105
Tim Peters2344fae2001-01-15 00:50:52 +0000106 self.cur is always a tuple. Each such tuple corresponds to a stack
107 frame that is currently active (self.cur[-2]). The following are the
108 definitions of its members. We use this external "parallel stack" to
109 avoid contaminating the program that we are profiling. (old profiler
110 used to write into the frames local dictionary!!) Derived classes
111 can change the definition of some entries, as long as they leave
112 [-2:] intact.
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000113
Tim Peters2344fae2001-01-15 00:50:52 +0000114 [ 0] = Time that needs to be charged to the parent frame's function.
115 It is used so that a function call will not have to access the
116 timing data for the parent frame.
117 [ 1] = Total time spent in this frame's function, excluding time in
118 subfunctions
119 [ 2] = Cumulative time spent in this frame's function, including time in
120 all subfunctions to this frame.
121 [-3] = Name of the function that corresponds to this frame.
122 [-2] = Actual frame that we correspond to (used to sync exception handling)
123 [-1] = Our parent 6-tuple (corresponds to frame.f_back)
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000124
Tim Peters2344fae2001-01-15 00:50:52 +0000125 Timing data for each function is stored as a 5-tuple in the dictionary
126 self.timings[]. The index is always the name stored in self.cur[4].
127 The following are the definitions of the members:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000128
Tim Peters2344fae2001-01-15 00:50:52 +0000129 [0] = The number of times this function was called, not counting direct
130 or indirect recursion,
131 [1] = Number of times this function appears on the stack, minus one
132 [2] = Total time spent internal to this function
133 [3] = Cumulative time that this function was present on the stack. In
134 non-recursive functions, this is the total execution time from start
135 to finish of each invocation of a function, including time spent in
136 all subfunctions.
137 [5] = A dictionary indicating for each function name, the number of times
138 it was called by us.
139 """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000140
Tim Peters2344fae2001-01-15 00:50:52 +0000141 def __init__(self, timer=None):
142 self.timings = {}
143 self.cur = None
144 self.cmd = ""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000145
Tim Peters2344fae2001-01-15 00:50:52 +0000146 if not timer:
147 if os.name == 'mac':
Tim Peters2344fae2001-01-15 00:50:52 +0000148 self.timer = MacOS.GetTicks
149 self.dispatcher = self.trace_dispatch_mac
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000150 self.get_time = _get_time_mac
Tim Peters2344fae2001-01-15 00:50:52 +0000151 elif hasattr(time, 'clock'):
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000152 self.timer = self.get_time = time.clock
Tim Peters2344fae2001-01-15 00:50:52 +0000153 self.dispatcher = self.trace_dispatch_i
154 elif hasattr(os, 'times'):
155 self.timer = os.times
156 self.dispatcher = self.trace_dispatch
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000157 self.get_time = _get_time_times
Tim Peters2344fae2001-01-15 00:50:52 +0000158 else:
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000159 self.timer = self.get_time = time.time
Tim Peters2344fae2001-01-15 00:50:52 +0000160 self.dispatcher = self.trace_dispatch_i
161 else:
162 self.timer = timer
163 t = self.timer() # test out timer function
164 try:
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000165 length = len(t)
166 except TypeError:
167 self.get_time = timer
168 self.dispatcher = self.trace_dispatch_i
169 else:
170 if length == 2:
Tim Peters2344fae2001-01-15 00:50:52 +0000171 self.dispatcher = self.trace_dispatch
172 else:
173 self.dispatcher = self.trace_dispatch_l
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000174 # This get_time() implementation needs to be defined
175 # here to capture the passed-in timer in the parameter
176 # list (for performance). Note that we can't assume
177 # the timer() result contains two values in all
178 # cases.
Guido van Rossume4deb952001-08-09 21:22:15 +0000179 import operator
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000180 def get_time_timer(timer=timer,
181 reduce=reduce, reducer=operator.add):
182 return reduce(reducer, timer(), 0)
183 self.get_time = get_time_timer
Tim Peters2344fae2001-01-15 00:50:52 +0000184 self.t = self.get_time()
185 self.simulate_call('profiler')
Guido van Rossumb6775db1994-08-01 11:34:53 +0000186
Tim Peters2344fae2001-01-15 00:50:52 +0000187 # Heavily optimized dispatch routine for os.times() timer
Guido van Rossumb6775db1994-08-01 11:34:53 +0000188
Tim Peters2344fae2001-01-15 00:50:52 +0000189 def trace_dispatch(self, frame, event, arg):
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000190 timer = self.timer
191 t = timer()
Tim Peters2344fae2001-01-15 00:50:52 +0000192 t = t[0] + t[1] - self.t # No Calibration constant
193 # t = t[0] + t[1] - self.t - .00053 # Calibration constant
194
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000195 if self.dispatch[event](self, frame,t):
196 t = timer()
Tim Peters2344fae2001-01-15 00:50:52 +0000197 self.t = t[0] + t[1]
198 else:
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000199 r = timer()
Tim Peters2344fae2001-01-15 00:50:52 +0000200 self.t = r[0] + r[1] - t # put back unrecorded delta
201 return
Guido van Rossumb6775db1994-08-01 11:34:53 +0000202
203
204
Tim Peters2344fae2001-01-15 00:50:52 +0000205 # Dispatch routine for best timer program (return = scalar integer)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000206
Tim Peters2344fae2001-01-15 00:50:52 +0000207 def trace_dispatch_i(self, frame, event, arg):
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000208 timer = self.timer
209 t = timer() - self.t # - 1 # Integer calibration constant
210 if self.dispatch[event](self, frame,t):
211 self.t = timer()
Tim Peters2344fae2001-01-15 00:50:52 +0000212 else:
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000213 self.t = timer() - t # put back unrecorded delta
Tim Peters2344fae2001-01-15 00:50:52 +0000214 return
Guido van Rossumcbf3dd51997-10-08 15:23:02 +0000215
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000216 # Dispatch routine for macintosh (timer returns time in ticks of
217 # 1/60th second)
Tim Peters2344fae2001-01-15 00:50:52 +0000218
219 def trace_dispatch_mac(self, frame, event, arg):
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000220 timer = self.timer
221 t = timer()/60.0 - self.t # - 1 # Integer calibration constant
222 if self.dispatch[event](self, frame,t):
223 self.t = timer()/60.0
Tim Peters2344fae2001-01-15 00:50:52 +0000224 else:
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000225 self.t = timer()/60.0 - t # put back unrecorded delta
Tim Peters2344fae2001-01-15 00:50:52 +0000226 return
Guido van Rossumb6775db1994-08-01 11:34:53 +0000227
228
Tim Peters2344fae2001-01-15 00:50:52 +0000229 # SLOW generic dispatch routine for timer returning lists of numbers
Guido van Rossumb6775db1994-08-01 11:34:53 +0000230
Tim Peters2344fae2001-01-15 00:50:52 +0000231 def trace_dispatch_l(self, frame, event, arg):
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000232 get_time = self.get_time
233 t = get_time() - self.t
Guido van Rossumb6775db1994-08-01 11:34:53 +0000234
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000235 if self.dispatch[event](self, frame,t):
236 self.t = get_time()
Tim Peters2344fae2001-01-15 00:50:52 +0000237 else:
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000238 self.t = get_time() - t # put back unrecorded delta
Tim Peters2344fae2001-01-15 00:50:52 +0000239 return
Guido van Rossumb6775db1994-08-01 11:34:53 +0000240
241
Tim Peters2344fae2001-01-15 00:50:52 +0000242 def trace_dispatch_exception(self, frame, t):
243 rt, rtt, rct, rfn, rframe, rcur = self.cur
244 if (not rframe is frame) and rcur:
245 return self.trace_dispatch_return(rframe, t)
246 return 0
Guido van Rossumb6775db1994-08-01 11:34:53 +0000247
248
Tim Peters2344fae2001-01-15 00:50:52 +0000249 def trace_dispatch_call(self, frame, t):
250 fcode = frame.f_code
251 fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name)
252 self.cur = (t, 0, 0, fn, frame, self.cur)
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000253 timings = self.timings
254 if timings.has_key(fn):
255 cc, ns, tt, ct, callers = timings[fn]
256 timings[fn] = cc, ns + 1, tt, ct, callers
Tim Peters2344fae2001-01-15 00:50:52 +0000257 else:
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000258 timings[fn] = 0, 0, 0, 0, {}
Tim Peters2344fae2001-01-15 00:50:52 +0000259 return 1
Guido van Rossumb6775db1994-08-01 11:34:53 +0000260
Tim Peters2344fae2001-01-15 00:50:52 +0000261 def trace_dispatch_return(self, frame, t):
262 # if not frame is self.cur[-2]: raise "Bad return", self.cur[3]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000263
Tim Peters2344fae2001-01-15 00:50:52 +0000264 # Prefix "r" means part of the Returning or exiting frame
265 # Prefix "p" means part of the Previous or older frame
Guido van Rossumb6775db1994-08-01 11:34:53 +0000266
Tim Peters2344fae2001-01-15 00:50:52 +0000267 rt, rtt, rct, rfn, frame, rcur = self.cur
268 rtt = rtt + t
269 sft = rtt + rct
Guido van Rossumb6775db1994-08-01 11:34:53 +0000270
Tim Peters2344fae2001-01-15 00:50:52 +0000271 pt, ptt, pct, pfn, pframe, pcur = rcur
272 self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
Guido van Rossumb6775db1994-08-01 11:34:53 +0000273
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000274 timings = self.timings
275 cc, ns, tt, ct, callers = timings[rfn]
Tim Peters2344fae2001-01-15 00:50:52 +0000276 if not ns:
277 ct = ct + sft
278 cc = cc + 1
279 if callers.has_key(pfn):
280 callers[pfn] = callers[pfn] + 1 # hack: gather more
281 # stats such as the amount of time added to ct courtesy
282 # of this specific call, and the contribution to cc
283 # courtesy of this call.
284 else:
285 callers[pfn] = 1
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000286 timings[rfn] = cc, ns - 1, tt+rtt, ct, callers
Guido van Rossumb6775db1994-08-01 11:34:53 +0000287
Tim Peters2344fae2001-01-15 00:50:52 +0000288 return 1
Guido van Rossumb6775db1994-08-01 11:34:53 +0000289
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000290
291 dispatch = {
292 "call": trace_dispatch_call,
293 "exception": trace_dispatch_exception,
294 "return": trace_dispatch_return,
295 }
296
297
Tim Peters2344fae2001-01-15 00:50:52 +0000298 # The next few function play with self.cmd. By carefully preloading
299 # our parallel stack, we can force the profiled result to include
300 # an arbitrary string as the name of the calling function.
301 # We use self.cmd as that string, and the resulting stats look
302 # very nice :-).
Guido van Rossumb6775db1994-08-01 11:34:53 +0000303
Tim Peters2344fae2001-01-15 00:50:52 +0000304 def set_cmd(self, cmd):
305 if self.cur[-1]: return # already set
306 self.cmd = cmd
307 self.simulate_call(cmd)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308
Tim Peters2344fae2001-01-15 00:50:52 +0000309 class fake_code:
310 def __init__(self, filename, line, name):
311 self.co_filename = filename
312 self.co_line = line
313 self.co_name = name
314 self.co_firstlineno = 0
Guido van Rossumb6775db1994-08-01 11:34:53 +0000315
Tim Peters2344fae2001-01-15 00:50:52 +0000316 def __repr__(self):
317 return repr((self.co_filename, self.co_line, self.co_name))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000318
Tim Peters2344fae2001-01-15 00:50:52 +0000319 class fake_frame:
320 def __init__(self, code, prior):
321 self.f_code = code
322 self.f_back = prior
Guido van Rossumb6775db1994-08-01 11:34:53 +0000323
Tim Peters2344fae2001-01-15 00:50:52 +0000324 def simulate_call(self, name):
325 code = self.fake_code('profile', 0, name)
326 if self.cur:
327 pframe = self.cur[-2]
328 else:
329 pframe = None
330 frame = self.fake_frame(code, pframe)
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000331 a = self.dispatch['call'](self, frame, 0)
Tim Peters2344fae2001-01-15 00:50:52 +0000332 return
Guido van Rossumb6775db1994-08-01 11:34:53 +0000333
Tim Peters2344fae2001-01-15 00:50:52 +0000334 # collect stats from pending stack, including getting final
335 # timings for self.cmd frame.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000336
Tim Peters2344fae2001-01-15 00:50:52 +0000337 def simulate_cmd_complete(self):
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000338 get_time = self.get_time
339 t = get_time() - self.t
Tim Peters2344fae2001-01-15 00:50:52 +0000340 while self.cur[-1]:
341 # We *can* cause assertion errors here if
342 # dispatch_trace_return checks for a frame match!
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000343 a = self.dispatch['return'](self, self.cur[-2], t)
Tim Peters2344fae2001-01-15 00:50:52 +0000344 t = 0
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000345 self.t = get_time() - t
Guido van Rossumb6775db1994-08-01 11:34:53 +0000346
347
Tim Peters2344fae2001-01-15 00:50:52 +0000348 def print_stats(self):
349 import pstats
350 pstats.Stats(self).strip_dirs().sort_stats(-1). \
351 print_stats()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000352
Tim Peters2344fae2001-01-15 00:50:52 +0000353 def dump_stats(self, file):
354 f = open(file, 'wb')
355 self.create_stats()
356 marshal.dump(self.stats, f)
357 f.close()
358
359 def create_stats(self):
360 self.simulate_cmd_complete()
361 self.snapshot_stats()
362
363 def snapshot_stats(self):
364 self.stats = {}
365 for func in self.timings.keys():
366 cc, ns, tt, ct, callers = self.timings[func]
367 callers = callers.copy()
368 nc = 0
369 for func_caller in callers.keys():
370 nc = nc + callers[func_caller]
371 self.stats[func] = cc, nc, tt, ct, callers
Guido van Rossumb6775db1994-08-01 11:34:53 +0000372
373
Tim Peters2344fae2001-01-15 00:50:52 +0000374 # The following two methods can be called by clients to use
375 # a profiler to profile a statement, given as a string.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000376
Tim Peters2344fae2001-01-15 00:50:52 +0000377 def run(self, cmd):
378 import __main__
379 dict = __main__.__dict__
380 return self.runctx(cmd, dict, dict)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000381
Tim Peters2344fae2001-01-15 00:50:52 +0000382 def runctx(self, cmd, globals, locals):
383 self.set_cmd(cmd)
384 sys.setprofile(self.dispatcher)
385 try:
386 exec cmd in globals, locals
387 finally:
388 sys.setprofile(None)
389 return self
Guido van Rossumb6775db1994-08-01 11:34:53 +0000390
Tim Peters2344fae2001-01-15 00:50:52 +0000391 # This method is more useful to profile a single function call.
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000392 def runcall(self, func, *args, **kw):
Tim Peters2344fae2001-01-15 00:50:52 +0000393 self.set_cmd(`func`)
394 sys.setprofile(self.dispatcher)
395 try:
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000396 return apply(func, args, kw)
Tim Peters2344fae2001-01-15 00:50:52 +0000397 finally:
398 sys.setprofile(None)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000399
Tim Peters2344fae2001-01-15 00:50:52 +0000400
401 #******************************************************************
402 # The following calculates the overhead for using a profiler. The
403 # problem is that it takes a fair amount of time for the profiler
404 # to stop the stopwatch (from the time it receives an event).
405 # Similarly, there is a delay from the time that the profiler
406 # re-starts the stopwatch before the user's code really gets to
407 # continue. The following code tries to measure the difference on
408 # a per-event basis. The result can the be placed in the
409 # Profile.dispatch_event() routine for the given platform. Note
410 # that this difference is only significant if there are a lot of
411 # events, and relatively little user code per event. For example,
412 # code with small functions will typically benefit from having the
413 # profiler calibrated for the current platform. This *could* be
414 # done on the fly during init() time, but it is not worth the
415 # effort. Also note that if too large a value specified, then
416 # execution time on some functions will actually appear as a
417 # negative number. It is *normal* for some functions (with very
418 # low call counts) to have such negative stats, even if the
419 # calibration figure is "correct."
420 #
421 # One alternative to profile-time calibration adjustments (i.e.,
422 # adding in the magic little delta during each event) is to track
423 # more carefully the number of events (and cumulatively, the number
424 # of events during sub functions) that are seen. If this were
425 # done, then the arithmetic could be done after the fact (i.e., at
426 # display time). Currently, we track only call/return events.
427 # These values can be deduced by examining the callees and callers
428 # vectors for each functions. Hence we *can* almost correct the
429 # internal time figure at print time (note that we currently don't
430 # track exception event processing counts). Unfortunately, there
431 # is currently no similar information for cumulative sub-function
432 # time. It would not be hard to "get all this info" at profiler
433 # time. Specifically, we would have to extend the tuples to keep
434 # counts of this in each frame, and then extend the defs of timing
435 # tuples to include the significant two figures. I'm a bit fearful
436 # that this additional feature will slow the heavily optimized
437 # event/time ratio (i.e., the profiler would run slower, fur a very
438 # low "value added" feature.)
439 #
440 # Plugging in the calibration constant doesn't slow down the
441 # profiler very much, and the accuracy goes way up.
442 #**************************************************************
443
444 def calibrate(self, m):
445 # Modified by Tim Peters
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000446 get_time = self.get_time
Tim Peters2344fae2001-01-15 00:50:52 +0000447 n = m
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000448 s = get_time()
Tim Peters2344fae2001-01-15 00:50:52 +0000449 while n:
450 self.simple()
451 n = n - 1
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000452 f = get_time()
Tim Peters2344fae2001-01-15 00:50:52 +0000453 my_simple = f - s
454 #print "Simple =", my_simple,
455
456 n = m
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000457 s = get_time()
Tim Peters2344fae2001-01-15 00:50:52 +0000458 while n:
459 self.instrumented()
460 n = n - 1
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000461 f = get_time()
Tim Peters2344fae2001-01-15 00:50:52 +0000462 my_inst = f - s
463 # print "Instrumented =", my_inst
464 avg_cost = (my_inst - my_simple)/m
465 #print "Delta/call =", avg_cost, "(profiler fixup constant)"
466 return avg_cost
467
468 # simulate a program with no profiler activity
469 def simple(self):
470 a = 1
471 pass
472
473 # simulate a program with call/return event processing
474 def instrumented(self):
475 a = 1
476 self.profiler_simulation(a, a, a)
477
478 # simulate an event processing activity (from user's perspective)
479 def profiler_simulation(self, x, y, z):
480 t = self.timer()
481 ## t = t[0] + t[1]
482 self.ut = t
Guido van Rossumb6775db1994-08-01 11:34:53 +0000483
484
485
Guido van Rossumb6775db1994-08-01 11:34:53 +0000486class OldProfile(Profile):
Tim Peters2344fae2001-01-15 00:50:52 +0000487 """A derived profiler that simulates the old style profile, providing
488 errant results on recursive functions. The reason for the usefulness of
489 this profiler is that it runs faster (i.e., less overhead). It still
490 creates all the caller stats, and is quite useful when there is *no*
491 recursion in the user's code.
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000492
Tim Peters2344fae2001-01-15 00:50:52 +0000493 This code also shows how easy it is to create a modified profiler.
494 """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000495
Tim Peters2344fae2001-01-15 00:50:52 +0000496 def trace_dispatch_exception(self, frame, t):
497 rt, rtt, rct, rfn, rframe, rcur = self.cur
498 if rcur and not rframe is frame:
499 return self.trace_dispatch_return(rframe, t)
500 return 0
Guido van Rossumb6775db1994-08-01 11:34:53 +0000501
Tim Peters2344fae2001-01-15 00:50:52 +0000502 def trace_dispatch_call(self, frame, t):
503 fn = `frame.f_code`
Guido van Rossumb6775db1994-08-01 11:34:53 +0000504
Tim Peters2344fae2001-01-15 00:50:52 +0000505 self.cur = (t, 0, 0, fn, frame, self.cur)
506 if self.timings.has_key(fn):
507 tt, ct, callers = self.timings[fn]
508 self.timings[fn] = tt, ct, callers
509 else:
510 self.timings[fn] = 0, 0, {}
511 return 1
Guido van Rossumb6775db1994-08-01 11:34:53 +0000512
Tim Peters2344fae2001-01-15 00:50:52 +0000513 def trace_dispatch_return(self, frame, t):
514 rt, rtt, rct, rfn, frame, rcur = self.cur
515 rtt = rtt + t
516 sft = rtt + rct
Guido van Rossumb6775db1994-08-01 11:34:53 +0000517
Tim Peters2344fae2001-01-15 00:50:52 +0000518 pt, ptt, pct, pfn, pframe, pcur = rcur
519 self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
520
521 tt, ct, callers = self.timings[rfn]
522 if callers.has_key(pfn):
523 callers[pfn] = callers[pfn] + 1
524 else:
525 callers[pfn] = 1
526 self.timings[rfn] = tt+rtt, ct + sft, callers
527
528 return 1
Guido van Rossumb6775db1994-08-01 11:34:53 +0000529
530
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000531 dispatch = {
532 "call": trace_dispatch_call,
533 "exception": trace_dispatch_exception,
534 "return": trace_dispatch_return,
535 }
536
537
Tim Peters2344fae2001-01-15 00:50:52 +0000538 def snapshot_stats(self):
539 self.stats = {}
540 for func in self.timings.keys():
541 tt, ct, callers = self.timings[func]
542 callers = callers.copy()
543 nc = 0
544 for func_caller in callers.keys():
545 nc = nc + callers[func_caller]
546 self.stats[func] = nc, nc, tt, ct, callers
Guido van Rossumb6775db1994-08-01 11:34:53 +0000547
Tim Peters2344fae2001-01-15 00:50:52 +0000548
Guido van Rossumb6775db1994-08-01 11:34:53 +0000549
Guido van Rossumb6775db1994-08-01 11:34:53 +0000550class HotProfile(Profile):
Tim Peters2344fae2001-01-15 00:50:52 +0000551 """The fastest derived profile example. It does not calculate
552 caller-callee relationships, and does not calculate cumulative
553 time under a function. It only calculates time spent in a
554 function, so it runs very quickly due to its very low overhead.
555 """
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000556
Tim Peters2344fae2001-01-15 00:50:52 +0000557 def trace_dispatch_exception(self, frame, t):
558 rt, rtt, rfn, rframe, rcur = self.cur
559 if rcur and not rframe is frame:
560 return self.trace_dispatch_return(rframe, t)
561 return 0
Guido van Rossumb6775db1994-08-01 11:34:53 +0000562
Tim Peters2344fae2001-01-15 00:50:52 +0000563 def trace_dispatch_call(self, frame, t):
564 self.cur = (t, 0, frame, self.cur)
565 return 1
Guido van Rossumb6775db1994-08-01 11:34:53 +0000566
Tim Peters2344fae2001-01-15 00:50:52 +0000567 def trace_dispatch_return(self, frame, t):
568 rt, rtt, frame, rcur = self.cur
Guido van Rossumb6775db1994-08-01 11:34:53 +0000569
Tim Peters2344fae2001-01-15 00:50:52 +0000570 rfn = `frame.f_code`
Guido van Rossumb6775db1994-08-01 11:34:53 +0000571
Tim Peters2344fae2001-01-15 00:50:52 +0000572 pt, ptt, pframe, pcur = rcur
573 self.cur = pt, ptt+rt, pframe, pcur
Guido van Rossumb6775db1994-08-01 11:34:53 +0000574
Tim Peters2344fae2001-01-15 00:50:52 +0000575 if self.timings.has_key(rfn):
576 nc, tt = self.timings[rfn]
577 self.timings[rfn] = nc + 1, rt + rtt + tt
578 else:
579 self.timings[rfn] = 1, rt + rtt
Guido van Rossumb6775db1994-08-01 11:34:53 +0000580
Tim Peters2344fae2001-01-15 00:50:52 +0000581 return 1
Guido van Rossumb6775db1994-08-01 11:34:53 +0000582
583
Fred Drakeedb5ffb2001-06-08 04:25:24 +0000584 dispatch = {
585 "call": trace_dispatch_call,
586 "exception": trace_dispatch_exception,
587 "return": trace_dispatch_return,
588 }
589
590
Tim Peters2344fae2001-01-15 00:50:52 +0000591 def snapshot_stats(self):
592 self.stats = {}
593 for func in self.timings.keys():
594 nc, tt = self.timings[func]
595 self.stats[func] = nc, nc, tt, 0, {}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000596
Tim Peters2344fae2001-01-15 00:50:52 +0000597
Guido van Rossumb6775db1994-08-01 11:34:53 +0000598
599#****************************************************************************
600def Stats(*args):
Tim Peters2344fae2001-01-15 00:50:52 +0000601 print 'Report generating functions are in the "pstats" module\a'
Guido van Rossumcc778eb1996-10-01 02:55:54 +0000602
603
604# When invoked as main program, invoke the profiler on a script
605if __name__ == '__main__':
Tim Peters2344fae2001-01-15 00:50:52 +0000606 if not sys.argv[1:]:
607 print "usage: profile.py scriptfile [arg] ..."
608 sys.exit(2)
Guido van Rossumcc778eb1996-10-01 02:55:54 +0000609
Tim Peters2344fae2001-01-15 00:50:52 +0000610 filename = sys.argv[1] # Get script filename
Guido van Rossumcc778eb1996-10-01 02:55:54 +0000611
Tim Peters2344fae2001-01-15 00:50:52 +0000612 del sys.argv[0] # Hide "profile.py" from argument list
Guido van Rossumcc778eb1996-10-01 02:55:54 +0000613
Tim Peters2344fae2001-01-15 00:50:52 +0000614 # Insert script directory in front of module search path
615 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumcc778eb1996-10-01 02:55:54 +0000616
Tim Peters2344fae2001-01-15 00:50:52 +0000617 run('execfile(' + `filename` + ')')