blob: 582bd8a7300143b738c8fdc8120b3eec6048f669 [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
10
11# Copyright 1994, by InfoSeek Corporation, all rights reserved.
12# Written by James Roskind
13#
14# Permission to use, copy, modify, and distribute this Python software
15# and its associated documentation for any purpose (subject to the
16# restriction in the following sentence) without fee is hereby granted,
17# provided that the above copyright notice appears in all copies, and
18# that both that copyright notice and this permission notice appear in
19# supporting documentation, and that the name of InfoSeek not be used in
20# advertising or publicity pertaining to distribution of the software
21# without specific, written prior permission. This permission is
22# explicitly restricted to the copying and modification of the software
23# to remain in Python, compiled Python, or other languages (such as C)
24# wherein the modified or derived code is exclusively imported into a
25# Python module.
26#
27# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
28# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
29# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
30# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
31# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
32# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
33# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
34
35
Guido van Rossum81762581992-04-21 15:36:23 +000036
37import sys
Guido van Rossum4e160981992-09-02 20:43:20 +000038import os
Guido van Rossumb6775db1994-08-01 11:34:53 +000039import time
Guido van Rossum4e160981992-09-02 20:43:20 +000040import string
Guido van Rossum4e160981992-09-02 20:43:20 +000041import marshal
Guido van Rossum81762581992-04-21 15:36:23 +000042
Guido van Rossum81762581992-04-21 15:36:23 +000043
Guido van Rossumb6775db1994-08-01 11:34:53 +000044# Global variables
45func_norm_dict = {}
46func_norm_counter = 0
Guido van Rossum4f399fb1995-09-30 16:48:54 +000047if hasattr(os, 'getpid'):
48 pid_string = `os.getpid()`
49else:
50 pid_string = ''
Guido van Rossum81762581992-04-21 15:36:23 +000051
Guido van Rossum81762581992-04-21 15:36:23 +000052
Guido van Rossumb6775db1994-08-01 11:34:53 +000053# Sample timer for use with
54#i_count = 0
55#def integer_timer():
56# global i_count
57# i_count = i_count + 1
58# return i_count
59#itimes = integer_timer # replace with C coded timer returning integers
Guido van Rossum81762581992-04-21 15:36:23 +000060
Guido van Rossumb6775db1994-08-01 11:34:53 +000061#**************************************************************************
62# The following are the static member functions for the profiler class
63# Note that an instance of Profile() is *not* needed to call them.
64#**************************************************************************
Guido van Rossum81762581992-04-21 15:36:23 +000065
Guido van Rossum4e160981992-09-02 20:43:20 +000066
67# simplified user interface
68def run(statement, *args):
Guido van Rossum7bc817d1993-12-17 15:25:27 +000069 prof = Profile()
Guido van Rossum4e160981992-09-02 20:43:20 +000070 try:
Guido van Rossumb6775db1994-08-01 11:34:53 +000071 prof = prof.run(statement)
Guido van Rossum4e160981992-09-02 20:43:20 +000072 except SystemExit:
73 pass
Guido van Rossumb6775db1994-08-01 11:34:53 +000074 if args:
Guido van Rossum4e160981992-09-02 20:43:20 +000075 prof.dump_stats(args[0])
Guido van Rossumb6775db1994-08-01 11:34:53 +000076 else:
77 return prof.print_stats()
Guido van Rossume61fa0a1993-10-22 13:56:35 +000078
79# print help
80def help():
81 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
92#**************************************************************************
93# class Profile documentation:
94#**************************************************************************
95# self.cur is always a tuple. Each such tuple corresponds to a stack
96# frame that is currently active (self.cur[-2]). The following are the
97# definitions of its members. We use this external "parallel stack" to
98# avoid contaminating the program that we are profiling. (old profiler
99# used to write into the frames local dictionary!!) Derived classes
100# can change the definition of some entries, as long as they leave
101# [-2:] intact.
102#
103# [ 0] = Time that needs to be charged to the parent frame's function. It is
104# used so that a function call will not have to access the timing data
105# for the parents frame.
106# [ 1] = Total time spent in this frame's function, excluding time in
107# subfunctions
108# [ 2] = Cumulative time spent in this frame's function, including time in
109# all subfunctions to this frame.
110# [-3] = Name of the function that corresonds to this frame.
111# [-2] = Actual frame that we correspond to (used to sync exception handling)
112# [-1] = Our parent 6-tuple (corresonds to frame.f_back)
113#**************************************************************************
114# Timing data for each function is stored as a 5-tuple in the dictionary
115# self.timings[]. The index is always the name stored in self.cur[4].
116# The following are the definitions of the members:
117#
118# [0] = The number of times this function was called, not counting direct
119# or indirect recursion,
120# [1] = Number of times this function appears on the stack, minus one
121# [2] = Total time spent internal to this function
122# [3] = Cumulative time that this function was present on the stack. In
123# non-recursive functions, this is the total execution time from start
124# to finish of each invocation of a function, including time spent in
125# all subfunctions.
126# [5] = A dictionary indicating for each function name, the number of times
127# it was called by us.
128#**************************************************************************
129# We produce function names via a repr() call on the f_code object during
130# profiling. This save a *lot* of CPU time. This results in a string that
131# always looks like:
132# <code object main at 87090, file "/a/lib/python-local/myfib.py", line 76>
133# After we "normalize it, it is a tuple of filename, line, function-name.
134# We wait till we are done profiling to do the normalization.
135# *IF* this repr format changes, then only the normalization routine should
136# need to be fixed.
137#**************************************************************************
138class Profile:
139
Guido van Rossum4f399fb1995-09-30 16:48:54 +0000140 def __init__(self, timer=None):
Guido van Rossumb6775db1994-08-01 11:34:53 +0000141 self.timings = {}
142 self.cur = None
143 self.cmd = ""
144
145 self.dispatch = { \
146 'call' : self.trace_dispatch_call, \
147 'return' : self.trace_dispatch_return, \
148 'exception': self.trace_dispatch_exception, \
149 }
150
Guido van Rossum4f399fb1995-09-30 16:48:54 +0000151 if not timer:
152 if hasattr(os, 'times'):
153 self.timer = os.times
154 self.dispatcher = self.trace_dispatch
155 else:
156 self.timer = time.time
157 self.dispatcher = self.trace_dispatch_i
Guido van Rossumb6775db1994-08-01 11:34:53 +0000158 else:
Guido van Rossum4f399fb1995-09-30 16:48:54 +0000159 self.timer = timer
Guido van Rossumb6775db1994-08-01 11:34:53 +0000160 t = self.timer() # test out timer function
161 try:
162 if len(t) == 2:
163 self.dispatcher = self.trace_dispatch
164 else:
Guido van Rossum4f399fb1995-09-30 16:48:54 +0000165 self.dispatcher = self.trace_dispatch_l
166 except TypeError:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000167 self.dispatcher = self.trace_dispatch_i
168 self.t = self.get_time()
169 self.simulate_call('profiler')
170
171
172 def get_time(self): # slow simulation of method to acquire time
173 t = self.timer()
174 if type(t) == type(()) or type(t) == type([]):
175 t = reduce(lambda x,y: x+y, t, 0)
176 return t
177
178
179 # Heavily optimized dispatch routine for os.times() timer
180
181 def trace_dispatch(self, frame, event, arg):
182 t = self.timer()
183 t = t[0] + t[1] - self.t # No Calibration constant
184 # t = t[0] + t[1] - self.t - .00053 # Calibration constant
185
186 if self.dispatch[event](frame,t):
187 t = self.timer()
188 self.t = t[0] + t[1]
189 else:
190 r = self.timer()
191 self.t = r[0] + r[1] - t # put back unrecorded delta
192 return
193
194
195
196 # Dispatch routine for best timer program (return = scalar integer)
197
198 def trace_dispatch_i(self, frame, event, arg):
199 t = self.timer() - self.t # - 1 # Integer calibration constant
200 if self.dispatch[event](frame,t):
201 self.t = self.timer()
202 else:
203 self.t = self.timer() - t # put back unrecorded delta
204 return
205
206
207 # SLOW generic dispatch rountine for timer returning lists of numbers
208
209 def trace_dispatch_l(self, frame, event, arg):
210 t = self.get_time() - self.t
211
212 if self.dispatch[event](frame,t):
213 self.t = self.get_time()
214 else:
215 self.t = self.get_time()-t # put back unrecorded delta
216 return
217
218
219 def trace_dispatch_exception(self, frame, t):
220 rt, rtt, rct, rfn, rframe, rcur = self.cur
221 if (not rframe is frame) and rcur:
222 return self.trace_dispatch_return(rframe, t)
223 return 0
224
225
226 def trace_dispatch_call(self, frame, t):
227 fn = `frame.f_code`
228
229 # The following should be about the best approach, but
230 # we would need a function that maps from id() back to
231 # the actual code object.
232 # fn = id(frame.f_code)
233 # Note we would really use our own function, which would
234 # return the code address, *and* bump the ref count. We
235 # would then fix up the normalize function to do the
236 # actualy repr(fn) call.
237
238 # The following is an interesting alternative
239 # It doesn't do as good a job, and it doesn't run as
240 # fast 'cause repr() is written in C, and this is Python.
241 #fcode = frame.f_code
242 #code = fcode.co_code
243 #if ord(code[0]) == 127: # == SET_LINENO
244 # # see "opcode.h" in the Python source
245 # fn = (fcode.co_filename, ord(code[1]) | \
246 # ord(code[2]) << 8, fcode.co_name)
247 #else:
248 # fn = (fcode.co_filename, 0, fcode.co_name)
249
250 self.cur = (t, 0, 0, fn, frame, self.cur)
251 if self.timings.has_key(fn):
252 cc, ns, tt, ct, callers = self.timings[fn]
253 self.timings[fn] = cc, ns + 1, tt, ct, callers
254 else:
255 self.timings[fn] = 0, 0, 0, 0, {}
256 return 1
257
258 def trace_dispatch_return(self, frame, t):
259 # if not frame is self.cur[-2]: raise "Bad return", self.cur[3]
260
261 # Prefix "r" means part of the Returning or exiting frame
262 # Prefix "p" means part of the Previous or older frame
263
264 rt, rtt, rct, rfn, frame, rcur = self.cur
265 rtt = rtt + t
266 sft = rtt + rct
267
268 pt, ptt, pct, pfn, pframe, pcur = rcur
269 self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
270
271 cc, ns, tt, ct, callers = self.timings[rfn]
272 if not ns:
273 ct = ct + sft
274 cc = cc + 1
275 if callers.has_key(pfn):
276 callers[pfn] = callers[pfn] + 1 # hack: gather more
277 # stats such as the amount of time added to ct courtesy
278 # of this specific call, and the contribution to cc
279 # courtesy of this call.
280 else:
281 callers[pfn] = 1
282 self.timings[rfn] = cc, ns - 1, tt+rtt, ct, callers
283
284 return 1
285
286 # The next few function play with self.cmd. By carefully preloading
287 # our paralell stack, we can force the profiled result to include
288 # an arbitrary string as the name of the calling function.
289 # We use self.cmd as that string, and the resulting stats look
290 # very nice :-).
291
292 def set_cmd(self, cmd):
293 if self.cur[-1]: return # already set
294 self.cmd = cmd
295 self.simulate_call(cmd)
296
297 class fake_code:
298 def __init__(self, filename, line, name):
299 self.co_filename = filename
300 self.co_line = line
301 self.co_name = name
302 self.co_code = '\0' # anything but 127
303
304 def __repr__(self):
305 return (self.co_filename, self.co_line, self.co_name)
306
307 class fake_frame:
308 def __init__(self, code, prior):
309 self.f_code = code
310 self.f_back = prior
311
312 def simulate_call(self, name):
313 code = self.fake_code('profile', 0, name)
314 if self.cur:
315 pframe = self.cur[-2]
316 else:
317 pframe = None
318 frame = self.fake_frame(code, pframe)
319 a = self.dispatch['call'](frame, 0)
320 return
321
322 # collect stats from pending stack, including getting final
323 # timings for self.cmd frame.
324
325 def simulate_cmd_complete(self):
326 t = self.get_time() - self.t
327 while self.cur[-1]:
328 # We *can* cause assertion errors here if
329 # dispatch_trace_return checks for a frame match!
330 a = self.dispatch['return'](self.cur[-2], t)
331 t = 0
332 self.t = self.get_time() - t
333
334
335 def print_stats(self):
336 import pstats
337 pstats.Stats(self).strip_dirs().sort_stats(-1). \
338 print_stats()
339
340 def dump_stats(self, file):
341 f = open(file, 'w')
342 self.create_stats()
343 marshal.dump(self.stats, f)
344 f.close()
345
346 def create_stats(self):
347 self.simulate_cmd_complete()
348 self.snapshot_stats()
349
350 def snapshot_stats(self):
351 self.stats = {}
352 for func in self.timings.keys():
353 cc, ns, tt, ct, callers = self.timings[func]
354 nor_func = self.func_normalize(func)
355 nor_callers = {}
356 nc = 0
357 for func_caller in callers.keys():
358 nor_callers[self.func_normalize(func_caller)]=\
359 callers[func_caller]
360 nc = nc + callers[func_caller]
361 self.stats[nor_func] = cc, nc, tt, ct, nor_callers
362
363
364 # Override the following function if you can figure out
365 # a better name for the binary f_code entries. I just normalize
366 # them sequentially in a dictionary. It would be nice if we could
367 # *really* see the name of the underlying C code :-). Sometimes
368 # you can figure out what-is-what by looking at caller and callee
369 # lists (and knowing what your python code does).
370
371 def func_normalize(self, func_name):
372 global func_norm_dict
373 global func_norm_counter
374 global func_sequence_num
375
376 if func_norm_dict.has_key(func_name):
377 return func_norm_dict[func_name]
378 if type(func_name) == type(""):
379 long_name = string.split(func_name)
Guido van Rossum4f399fb1995-09-30 16:48:54 +0000380 file_name = long_name[-3][1:-2]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000381 func = long_name[2]
Guido van Rossum4f399fb1995-09-30 16:48:54 +0000382 lineno = long_name[-1][:-1]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000383 if '?' == func: # Until I find out how to may 'em...
384 file_name = 'python'
385 func_norm_counter = func_norm_counter + 1
386 func = pid_string + ".C." + `func_norm_counter`
387 result = file_name , string.atoi(lineno) , func
388 else:
389 result = func_name
390 func_norm_dict[func_name] = result
391 return result
392
393
394 # The following two methods can be called by clients to use
395 # a profiler to profile a statement, given as a string.
396
397 def run(self, cmd):
398 import __main__
399 dict = __main__.__dict__
Guido van Rossum6cb84f31996-05-28 23:00:42 +0000400 return self.runctx(cmd, dict, dict)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000401
402 def runctx(self, cmd, globals, locals):
403 self.set_cmd(cmd)
Guido van Rossum4f399fb1995-09-30 16:48:54 +0000404 sys.setprofile(self.dispatcher)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000405 try:
Guido van Rossum9c3241d1995-08-10 19:46:50 +0000406 exec cmd in globals, locals
Guido van Rossumb6775db1994-08-01 11:34:53 +0000407 finally:
408 sys.setprofile(None)
Guido van Rossum6cb84f31996-05-28 23:00:42 +0000409 return self
Guido van Rossumb6775db1994-08-01 11:34:53 +0000410
411 # This method is more useful to profile a single function call.
412 def runcall(self, func, *args):
Guido van Rossum8afa8241995-06-22 18:52:35 +0000413 self.set_cmd(`func`)
Guido van Rossum4f399fb1995-09-30 16:48:54 +0000414 sys.setprofile(self.dispatcher)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000415 try:
Guido van Rossum6cb84f31996-05-28 23:00:42 +0000416 return apply(func, args)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000417 finally:
418 sys.setprofile(None)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000419
420
421 #******************************************************************
422 # The following calculates the overhead for using a profiler. The
423 # problem is that it takes a fair amount of time for the profiler
424 # to stop the stopwatch (from the time it recieves an event).
425 # Similarly, there is a delay from the time that the profiler
426 # re-starts the stopwatch before the user's code really gets to
427 # continue. The following code tries to measure the difference on
428 # a per-event basis. The result can the be placed in the
429 # Profile.dispatch_event() routine for the given platform. Note
430 # that this difference is only significant if there are a lot of
431 # events, and relatively little user code per event. For example,
432 # code with small functions will typically benefit from having the
433 # profiler calibrated for the current platform. This *could* be
434 # done on the fly during init() time, but it is not worth the
435 # effort. Also note that if too large a value specified, then
436 # execution time on some functions will actually appear as a
437 # negative number. It is *normal* for some functions (with very
438 # low call counts) to have such negative stats, even if the
439 # calibration figure is "correct."
440 #
441 # One alternative to profile-time calibration adjustments (i.e.,
442 # adding in the magic little delta during each event) is to track
443 # more carefully the number of events (and cumulatively, the number
444 # of events during sub functions) that are seen. If this were
445 # done, then the arithmetic could be done after the fact (i.e., at
446 # display time). Currintly, we track only call/return events.
447 # These values can be deduced by examining the callees and callers
448 # vectors for each functions. Hence we *can* almost correct the
449 # internal time figure at print time (note that we currently don't
450 # track exception event processing counts). Unfortunately, there
451 # is currently no similar information for cumulative sub-function
452 # time. It would not be hard to "get all this info" at profiler
453 # time. Specifically, we would have to extend the tuples to keep
454 # counts of this in each frame, and then extend the defs of timing
455 # tuples to include the significant two figures. I'm a bit fearful
456 # that this additional feature will slow the heavily optimized
457 # event/time ratio (i.e., the profiler would run slower, fur a very
458 # low "value added" feature.)
459 #
460 # Plugging in the calibration constant doesn't slow down the
461 # profiler very much, and the accuracy goes way up.
462 #**************************************************************
463
464 def calibrate(self, m):
465 n = m
466 s = self.timer()
467 while n:
468 self.simple()
469 n = n - 1
470 f = self.timer()
471 my_simple = f[0]+f[1]-s[0]-s[1]
472 #print "Simple =", my_simple,
473
474 n = m
475 s = self.timer()
476 while n:
477 self.instrumented()
478 n = n - 1
479 f = self.timer()
480 my_inst = f[0]+f[1]-s[0]-s[1]
481 # print "Instrumented =", my_inst
482 avg_cost = (my_inst - my_simple)/m
483 #print "Delta/call =", avg_cost, "(profiler fixup constant)"
484 return avg_cost
485
486 # simulate a program with no profiler activity
487 def simple(self):
488 a = 1
489 pass
490
491 # simulate a program with call/return event processing
492 def instrumented(self):
493 a = 1
494 self.profiler_simulation(a, a, a)
495
496 # simulate an event processing activity (from user's perspective)
497 def profiler_simulation(self, x, y, z):
498 t = self.timer()
499 t = t[0] + t[1]
500 self.ut = t
501
502
503
504#****************************************************************************
505# OldProfile class documentation
506#****************************************************************************
507#
508# The following derived profiler simulates the old style profile, providing
509# errant results on recursive functions. The reason for the usefulnes of this
510# profiler is that it runs faster (i.e., less overhead). It still creates
511# all the caller stats, and is quite useful when there is *no* recursion
512# in the user's code.
513#
514# This code also shows how easy it is to create a modified profiler.
515#****************************************************************************
516class OldProfile(Profile):
517 def trace_dispatch_exception(self, frame, t):
518 rt, rtt, rct, rfn, rframe, rcur = self.cur
519 if rcur and not rframe is frame:
520 return self.trace_dispatch_return(rframe, t)
521 return 0
522
523 def trace_dispatch_call(self, frame, t):
524 fn = `frame.f_code`
525
526 self.cur = (t, 0, 0, fn, frame, self.cur)
527 if self.timings.has_key(fn):
528 tt, ct, callers = self.timings[fn]
529 self.timings[fn] = tt, ct, callers
530 else:
531 self.timings[fn] = 0, 0, {}
532 return 1
533
534 def trace_dispatch_return(self, frame, t):
535 rt, rtt, rct, rfn, frame, rcur = self.cur
536 rtt = rtt + t
537 sft = rtt + rct
538
539 pt, ptt, pct, pfn, pframe, pcur = rcur
540 self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
541
542 tt, ct, callers = self.timings[rfn]
543 if callers.has_key(pfn):
544 callers[pfn] = callers[pfn] + 1
545 else:
546 callers[pfn] = 1
547 self.timings[rfn] = tt+rtt, ct + sft, callers
548
549 return 1
550
551
552 def snapshot_stats(self):
553 self.stats = {}
554 for func in self.timings.keys():
555 tt, ct, callers = self.timings[func]
556 nor_func = self.func_normalize(func)
557 nor_callers = {}
558 nc = 0
559 for func_caller in callers.keys():
560 nor_callers[self.func_normalize(func_caller)]=\
561 callers[func_caller]
562 nc = nc + callers[func_caller]
563 self.stats[nor_func] = nc, nc, tt, ct, nor_callers
564
565
566
567#****************************************************************************
568# HotProfile class documentation
569#****************************************************************************
570#
571# This profiler is the fastest derived profile example. It does not
572# calculate caller-callee relationships, and does not calculate cumulative
573# time under a function. It only calculates time spent in a function, so
574# it runs very quickly (re: very low overhead)
575#****************************************************************************
576class HotProfile(Profile):
577 def trace_dispatch_exception(self, frame, t):
578 rt, rtt, rfn, rframe, rcur = self.cur
579 if rcur and not rframe is frame:
580 return self.trace_dispatch_return(rframe, t)
581 return 0
582
583 def trace_dispatch_call(self, frame, t):
584 self.cur = (t, 0, frame, self.cur)
585 return 1
586
587 def trace_dispatch_return(self, frame, t):
588 rt, rtt, frame, rcur = self.cur
589
590 rfn = `frame.f_code`
591
592 pt, ptt, pframe, pcur = rcur
593 self.cur = pt, ptt+rt, pframe, pcur
594
595 if self.timings.has_key(rfn):
596 nc, tt = self.timings[rfn]
597 self.timings[rfn] = nc + 1, rt + rtt + tt
598 else:
599 self.timings[rfn] = 1, rt + rtt
600
601 return 1
602
603
604 def snapshot_stats(self):
605 self.stats = {}
606 for func in self.timings.keys():
607 nc, tt = self.timings[func]
608 nor_func = self.func_normalize(func)
609 self.stats[nor_func] = nc, nc, tt, 0, {}
610
611
612
613#****************************************************************************
614def Stats(*args):
615 print 'Report generating functions are in the "pstats" module\a'
Guido van Rossumcc778eb1996-10-01 02:55:54 +0000616
617
618# When invoked as main program, invoke the profiler on a script
619if __name__ == '__main__':
620 import sys
621 import os
622 if not sys.argv[1:]:
623 print "usage: profile.py scriptfile [arg] ..."
624 sys.exit(2)
625
626 filename = sys.argv[1] # Get script filename
627
628 del sys.argv[0] # Hide "profile.py" from argument list
629
630 # Insert script directory in front of module search path
631 sys.path.insert(0, os.path.dirname(filename))
632
633 run('execfile(' + `filename` + ')')