blob: 5a4601a14975df2c46fd29ebbc60010e40bdb6fc [file] [log] [blame]
Guido van Rossumadb31051994-06-23 11:42:52 +00001#
2# Class for printing reports on profiled python code. rev 1.0 4/1/94
3#
4# Based on prior profile module by Sjoerd Mullender...
5# which was hacked somewhat by: Guido van Rossum
6#
7# see jprofile.doc and jprofile.py for more info.
8
9# Copyright 1994, by InfoSeek Corporation, all rights reserved.
10# Written by James Roskind
11#
12# Permission to use, copy, modify, and distribute this Python software
13# and its associated documentation for any purpose (subject to the
14# restriction in the following sentence) without fee is hereby granted,
15# provided that the above copyright notice appears in all copies, and
16# that both that copyright notice and this permission notice appear in
17# supporting documentation, and that the name of InfoSeek not be used in
18# advertising or publicity pertaining to distribution of the software
19# without specific, written prior permission. This permission is
20# explicitly restricted to the copying and modification of the software
21# to remain in Python, compiled Python, or other languages (such as C)
22# wherein the modified or derived code is exclusively imported into a
23# Python module.
24#
25# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
26# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
27# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
28# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
29# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
30# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
31# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
32
33
34import os
35import time
36import string
37import marshal
38import regex
39
40#**************************************************************************
41# Class Stats documentation
42#**************************************************************************
43# This class is used for creating reports from data generated by the
44# Profile class. It is a "friend" of that class, and imports data either
45# by direct access to members of Profile class, or by reading in a dictionary
46# that was emitted (via marshal) from the Profile class.
47#
48# The big change from the previous Profiler (in terms of raw functionality)
49# is that an "add()" method has been provided to combine Stats from
50# several distinct profile runs. Both the constructor and the add()
51# method now take arbitrarilly many file names as arguments.
52#
53# All the print methods now take an argument that indicats how many lines
54# to print. If the arg is a floating point number between 0 and 1.0, then
55# it is taken as a decimal percentage of the availabel lines to be printed
56# (e.g., .1 means print 10% of all available lines). If it is an integer,
57# it is taken to mean the number of lines of data that you wish to have
58# printed.
59#
60# The sort_stats() method now processes some additionaly options (i.e., in
61# addition to the old -1, 0, 1, or 2). It takes an arbitrary number of quoted
62# strings to select the sort order. For example sort_stats('time', 'name')
63# sorts on the major key of "internal function time", and on the minor
64# key of 'the name of the function'. Look at the two tables in sort_stats()
65# and get_sort_arg_defs(self) for more examples.
66#
67# All methods now return "self", so you can string together commands like:
68# Stats('foo', 'goo').strip_dirs().sort_stats('calls').\
69# print_stats(5).print_callers(5)
70#
71#**************************************************************************
72import fpformat
73
74class Stats:
75 def __init__(self, *args):
76 if not len(args):
77 arg = None
78 else:
79 arg = args[0]
80 args = args[1:]
81 self.init(arg)
82 apply(self.add, args).ignore()
83
84 def init(self, arg):
85 self.all_callees = None # calc only if needed
86 self.files = []
87 self.fcn_list = None
88 self.total_tt = 0
89 self.total_calls = 0
90 self.prim_calls = 0
91 self.max_name_len = 0
92 self.top_level = {}
93 self.stats = {}
94 self.sort_arg_dict = {}
95 self.load_stats(arg)
96 trouble = 1
97 try:
98 self.get_top_level_stats()
99 trouble = 0
100 finally:
101 if trouble:
102 print "Invalid timing data",
103 if self.files: print self.files[-1],
104 print
105
106
107 def load_stats(self, arg):
108 if not arg: self.stats = {}
109 elif type(arg) == type(""):
110 f = open(arg, 'r')
111 self.stats = marshal.load(f)
112 f.close()
113 try:
114 file_stats = os.stat(arg)
115 arg = time.ctime(file_stats[8]) + " " + arg
116 except: # in case this is not unix
117 pass
118 self.files = [ arg ]
119 elif type(arg) == type(self):
120 try:
121 arg.create_stats()
122 self.stats = arg.stats
123 arg.stats = {}
124 except:
125 pass
126 if not self.stats:
127 raise TypeError, "Cannot create or construct a " \
128 + `self.__class__` \
129 + " object from '" + `arg` + "'"
130 return
131
132 def get_top_level_stats(self):
133 for func in self.stats.keys():
134 cc, nc, tt, ct, callers = self.stats[func]
135 self.total_calls = self.total_calls + nc
136 self.prim_calls = self.prim_calls + cc
137 self.total_tt = self.total_tt + tt
138 if callers.has_key(("jprofile", 0, "profiler")):
139 self.top_level[func] = None
140 if len(func_std_string(func)) > self.max_name_len:
141 self.max_name_len = len(func_std_string(func))
142
143 def add(self, *arg_list):
144 if not arg_list: return self
145 if len(arg_list) > 1: apply(self.add, arg_list[1:])
146 other = arg_list[0]
147 if type(self) != type(other) or \
148 self.__class__ != other.__class__:
149 other = Stats(other)
150 self.files = self.files + other.files
151 self.total_calls = self.total_calls + other.total_calls
152 self.prim_calls = self.prim_calls + other.prim_calls
153 self.total_tt = self.total_tt + other.total_tt
154 for func in other.top_level.keys():
155 self.top_level[func] = None
156
157 if self.max_name_len < other.max_name_len:
158 self.max_name_len = other.max_name_len
159
160 self.fcn_list = None
161
162 for func in other.stats.keys():
163 if self.stats.has_key(func):
164 old_func_stat = self.stats[func]
165 else:
166 old_func_stat = (0, 0, 0, 0, {},)
167 self.stats[func] = add_func_stats(old_func_stat, \
168 other.stats[func])
169 return self
170
171
172
173 # list the tuple indicies and directions for sorting,
174 # along with some printable description
175 sort_arg_dict_default = {\
176 "calls" : (((1,-1), ), "call count"),\
177 "cumulative": (((3,-1), ), "cumulative time"),\
178 "file" : (((4, 1), ), "file name"),\
179 "line" : (((5, 1), ), "line number"),\
180 "module" : (((4, 1), ), "file name"),\
181 "name" : (((6, 1), ), "function name"),\
182 "nfl" : (((6, 1),(4, 1),(5, 1),), "name/file/line"), \
183 "pcalls" : (((0,-1), ), "call count"),\
184 "stdname" : (((7, 1), ), "standard name"),\
185 "time" : (((2,-1), ), "internal time"),\
186 }
187
188 # Expand all abbreviations that are unique
189 def get_sort_arg_defs(self):
190 if not self.sort_arg_dict:
191 self.sort_arg_dict = dict = {}
192 std_list = dict.keys()
193 bad_list = {}
194 for word in self.sort_arg_dict_default.keys():
195 fragment = word
196 while fragment:
197 if not fragment:
198 break
199 if dict.has_key(fragment):
200 bad_list[fragment] = 0
201 break
202 dict[fragment] = self. \
203 sort_arg_dict_default[word]
204 fragment = fragment[:-1]
205 for word in bad_list.keys():
206 del dict[word]
207 return self.sort_arg_dict
208
209
210 def sort_stats(self, *field):
211 if not field:
212 self.fcn_list = 0
213 return self
214 if len(field) == 1 and type(field[0]) == type(1):
215 # Be compatible with old profiler
216 field = [ {-1: "stdname", \
217 0:"calls", \
218 1:"time", \
219 2: "cumulative" } [ field[0] ] ]
220
221 sort_arg_defs = self.get_sort_arg_defs()
222 sort_tuple = ()
223 self.sort_type = ""
224 connector = ""
225 for word in field:
226 sort_tuple = sort_tuple + sort_arg_defs[word][0]
227 self.sort_type = self.sort_type + connector + \
228 sort_arg_defs[word][1]
229 connector = ", "
230
231 stats_list = []
232 for func in self.stats.keys():
233 cc, nc, tt, ct, callers = self.stats[func]
234 stats_list.append((cc, nc, tt, ct) + func_split(func) \
235 + (func_std_string(func), func,) )
236
237 stats_list.sort(TupleComp(sort_tuple).compare)
238
239 self.fcn_list = fcn_list = []
240 for tuple in stats_list:
241 fcn_list.append(tuple[-1])
242 return self
243
244
245 def reverse_order(self):
246 if self.fcn_list: self.fcn_list.reverse()
247 return self
248
249 def strip_dirs(self):
250 oldstats = self.stats
251 self.stats = newstats = {}
252 max_name_len = 0
253 for func in oldstats.keys():
254 cc, nc, tt, ct, callers = oldstats[func]
255 newfunc = func_strip_path(func)
256 if len(func_std_string(newfunc)) > max_name_len:
257 max_name_len = len(func_std_string(newfunc))
258 newcallers = {}
259 for func2 in callers.keys():
260 newcallers[func_strip_path(func2)] = \
261 callers[func2]
262
263 if newstats.has_key(newfunc):
264 newstats[newfunc] = add_func_stats( \
265 newstats[newfunc],\
266 (cc, nc, tt, ct, newcallers))
267 else:
268 newstats[newfunc] = (cc, nc, tt, ct, newcallers)
269 old_top = self.top_level
270 self.top_level = new_top = {}
271 for func in old_top.keys():
272 new_top[func_strip_path(func)] = None
273
274 self.max_name_len = max_name_len
275
276 self.fcn_list = None
277 self.all_callees = None
278 return self
279
280
281
282 def calc_callees(self):
283 if self.all_callees: return
284 self.all_callees = all_callees = {}
285 for func in self.stats.keys():
286 if not all_callees.has_key(func):
287 all_callees[func] = {}
288 cc, nc, tt, ct, callers = self.stats[func]
289 for func2 in callers.keys():
290 if not all_callees.has_key(func2):
291 all_callees[func2] = {}
292 all_callees[func2][func] = callers[func2]
293 return
294
295 #******************************************************************
296 # The following functions support actual printing of reports
297 #******************************************************************
298
299 # Optional "amount" is either a line count, or a percentage of lines.
300
301 def eval_print_amount(self, sel, list, msg):
302 new_list = list
303 if type(sel) == type(""):
304 new_list = []
305 for func in list:
306 if 0<=regex.search(sel, func_std_string(func)):
307 new_list.append(func)
308 else:
309 count = len(list)
310 if type(sel) == type(1.0) and 0.0 <= sel < 1.0:
311 count = int (count * sel + .5)
312 new_list = list[:count]
313 elif type(sel) == type(1) and 0 <= sel < count:
314 count = sel
315 new_list = list[:count]
316 if len(list) != len(new_list):
317 msg = msg + " List reduced from " + `len(list)` \
318 + " to " + `len(new_list)` + \
319 " due to restriction <" + `sel` + ">\n"
320
321 return new_list, msg
322
323
324
325 def get_print_list(self, sel_list):
326 width = self.max_name_len
327 if self.fcn_list:
328 list = self.fcn_list[:]
329 msg = " Ordered by: " + self.sort_type + '\n'
330 else:
331 list = self.stats.keys()
332 msg = " Random listing order was used\n"
333
334 for selection in sel_list:
335 list,msg = self.eval_print_amount(selection, list, msg)
336
337 count = len(list)
338
339 if not list:
340 return 0, list
341 print msg
342 if count < len(self.stats):
343 width = 0
344 for func in list:
345 if len(func_std_string(func)) > width:
346 width = len(func_std_string(func))
347 return width+2, list
348
349 def print_stats(self, *amount):
350 for filename in self.files:
351 print filename
352 if self.files: print
353 indent = " "
354 for func in self.top_level.keys():
355 print indent, func_get_function_name(func)
356
357 print indent, self.total_calls, "function calls",
358 if self.total_calls != self.prim_calls:
359 print "(" + `self.prim_calls`, "primitive calls)",
360 print "in", fpformat.fix(self.total_tt, 3), "CPU seconds"
361 print
362 width, list = self.get_print_list(amount)
363 if list:
364 self.print_title()
365 for func in list:
366 self.print_line(func)
367 print
368 print
369 return self
370
371
372 def print_callees(self, *amount):
373 width, list = self.get_print_list(amount)
374 if list:
375 self.calc_callees()
376
377 self.print_call_heading(width, "called...")
378 for func in list:
379 if self.all_callees.has_key(func):
380 self.print_call_line(width, \
381 func, self.all_callees[func])
382 else:
383 self.print_call_line(width, func, {})
384 print
385 print
386 return self
387
388 def print_callers(self, *amount):
389 width, list = self.get_print_list(amount)
390 if list:
391 self.print_call_heading(width, "was called by...")
392 for func in list:
393 cc, nc, tt, ct, callers = self.stats[func]
394 self.print_call_line(width, func, callers)
395 print
396 print
397 return self
398
399 def print_call_heading(self, name_size, column_title):
400 print string.ljust("Function ", name_size) + column_title
401
402
403 def print_call_line(self, name_size, source, call_dict):
404 print string.ljust(func_std_string(source), name_size),
405 if not call_dict:
406 print "--"
407 return
408 clist = call_dict.keys()
409 clist.sort()
410 name_size = name_size + 1
411 indent = ""
412 for func in clist:
413 name = func_std_string(func)
414 print indent*name_size + name + '(' \
415 + `call_dict[func]`+')', \
416 f8(self.stats[func][3])
417 indent = " "
418
419
420
421 def print_title(self):
422 print string.rjust('ncalls', 9),
423 print string.rjust('tottime', 8),
424 print string.rjust('percall', 8),
425 print string.rjust('cumtime', 8),
426 print string.rjust('percall', 8),
427 print 'filename:lineno(function)'
428
429
430 def print_line(self, func): # hack : should print percentages
431 cc, nc, tt, ct, callers = self.stats[func]
432 c = `nc`
433 if nc != cc:
434 c = c + '/' + `cc`
435 print string.rjust(c, 9),
436 print f8(tt),
437 if nc == 0:
438 print ' '*8,
439 else:
440 print f8(tt/nc),
441 print f8(ct),
442 if cc == 0:
443 print ' '*8,
444 else:
445 print f8(ct/cc),
446 print func_std_string(func)
447
448
449 def ignore(self):
450 pass # has no return value, so use at end of line :-)
451
452
453#**************************************************************************
454# class TupleComp Documentation
455#**************************************************************************
456# This class provides a generic function for comparing any two tuples.
457# Each instance records a list of tuple-indicies (from most significant
458# to least significant), and sort direction (ascending or decending) for
459# each tuple-index. The compare functions can then be used as the function
460# argument to the system sort() function when a list of tuples need to be
461# sorted in the instances order.
462#**************************************************************************
463class TupleComp:
464 def __init__(self, comp_select_list):
465 self.comp_select_list = comp_select_list
466
467 def compare (self, left, right):
468 for index, direction in self.comp_select_list:
469 l = left[index]
470 r = right[index]
471 if l < r:
472 return -direction
473 if l > r:
474 return direction
475 return 0
476
477
478
479#**************************************************************************
480
481def func_strip_path(func_name):
482 file, line, name = func_name
483 return os.path.basename(file), line, name
484
485def func_get_function_name(func):
486 return func[2]
487
488def func_std_string(func_name): # match what old profile produced
489 file, line, name = func_name
490 return file + ":" + `line` + "(" + name + ")"
491
492def func_split(func_name):
493 return func_name
494
495#**************************************************************************
496# The following functions combine statists for pairs functions.
497# The bulk of the processing involves correctly handling "call" lists,
498# such as callers and callees.
499#**************************************************************************
500
501 # Add together all the stats for two profile entries
502def add_func_stats(target, source):
503 cc, nc, tt, ct, callers = source
504 t_cc, t_nc, t_tt, t_ct, t_callers = target
505 return (cc+t_cc, nc+t_nc, tt+t_tt, ct+t_ct, \
506 add_callers(t_callers, callers))
507
508
509 # Combine two caller lists in a single list.
510def add_callers(target, source):
511 new_callers = {}
512 for func in target.keys():
513 new_callers[func] = target[func]
514 for func in source.keys():
515 if new_callers.has_key(func):
516 new_callers[func] = source[func] + new_callers[func]
517 else:
518 new_callers[func] = source[func]
519 return new_callers
520
521 # Sum the caller statistics to get total number of calls recieved
522def count_calls(callers):
523 nc = 0
524 for func in callers.keys():
525 nc = nc + callers[func]
526 return nc
527
528#**************************************************************************
529# The following functions support printing of reports
530#**************************************************************************
531
532def f8(x):
533 return string.rjust(fpformat.fix(x, 3), 8)
534
535