1
# Copyright (C) 2006, 2008, 2009, 2010 by Canonical Ltd
2
# Written by John Arbash Meinel <john@arbash-meinel.com>
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
"""A custom importer and regex compiler which logs time spent."""
32
if sys.platform == 'win32':
36
def stack_add(name, frame_name, frame_lineno, scope_name=None):
37
"""Start a new record on the stack"""
40
this_stack = (_cur_id, name)
43
_total_stack[_parent_stack[-1]].append(this_stack)
44
_total_stack[this_stack] = []
45
_parent_stack.append(this_stack)
46
_info[this_stack] = [len(_parent_stack)-1, frame_name, frame_lineno, scope_name]
51
def stack_finish(this, cost):
52
"""Finish a given entry, and record its cost in time"""
55
assert _parent_stack[-1] == this, \
56
'import stack does not end with this %s: %s' % (this, _parent_stack)
58
_info[this].append(cost)
61
def log_stack_info(out_file, sorted=True, hide_fast=True):
62
# Find all of the roots with import = 0
63
out_file.write('%5s %5s %-40s @ %s:%s\n'
64
% ('cum', 'inline', 'name', 'file', 'line'))
65
todo = [(value[-1], key) for key,value in _info.iteritems() if value[0] == 0]
71
cum_time, cur = todo.pop()
72
children = _total_stack[cur]
77
if hide_fast and info[-1] < 0.0001:
80
# Compute the module time by removing the children times
82
for child in children:
84
mod_time -= c_info[-1]
85
c_times.append((c_info[-1], child))
87
# indent, cum_time, mod_time, name,
88
# scope_name, frame_name, frame_lineno
89
out_file.write('%5.1f %5.1f %-40s @ %s:%d\n'
90
% (info[-1]*1000., mod_time*1000.,
91
('+'*info[0] + cur[1]),
101
_real_import = __import__
103
def timed_import(name, globals=None, locals=None, fromlist=None, level=-1):
104
"""Wrap around standard importer to log import time"""
105
# normally there are 4, but if this is called as __import__ eg by
106
# /usr/lib/python2.6/email/__init__.py then there may be only one
108
# level is only passed by python2.6
111
# can't determine the scope name afaics; we could peek up the stack to
112
# see where this is being called from, but it should be a rare case.
115
scope_name = globals.get('__name__', None)
116
if scope_name is None:
117
scope_name = globals.get('__file__', None)
118
if scope_name is None:
119
scope_name = globals.keys()
121
# Trim out paths before breezy
122
loc = scope_name.find('breezy')
124
scope_name = scope_name[loc:]
125
# For stdlib, trim out early paths
126
loc = scope_name.find('python2.4')
128
scope_name = scope_name[loc:]
130
# Figure out the frame that is doing the importing
131
frame = sys._getframe(1)
132
frame_name = frame.f_globals.get('__name__', '<unknown>')
134
if frame_name.endswith('demandload'):
135
# If this was demandloaded, we have 3 frames to ignore
136
extra = '(demandload) '
137
frame = sys._getframe(4)
138
frame_name = frame.f_globals.get('__name__', '<unknown>')
139
elif frame_name.endswith('lazy_import'):
140
# If this was lazily imported, we have 3 frames to ignore
142
frame = sys._getframe(4)
143
frame_name = frame.f_globals.get('__name__', '<unknown>')
145
extra += ' [%s]' % (', '.join(map(str, fromlist)),)
146
frame_lineno = frame.f_lineno
148
this = stack_add(extra + name, frame_name, frame_lineno, scope_name)
153
return _real_import(name, globals, locals, fromlist, level=level)
155
tload = _timer()-tstart
156
stack_finish(this, tload)
159
def _repr_regexp(pattern, max_len=30):
160
"""Present regexp pattern for logging, truncating if over max_len."""
161
if len(pattern) > max_len:
162
return repr(pattern[:max_len-3]) + "..."
166
_real_compile = re._compile
169
def timed_compile(*args, **kwargs):
170
"""Log how long it takes to compile a regex"""
172
# And who is requesting this?
173
frame = sys._getframe(2)
174
frame_name = frame.f_globals.get('__name__', '<unknown>')
177
if frame_name.endswith('lazy_regex'):
178
# If this was lazily compiled, we have 3 more frames to ignore
180
frame = sys._getframe(5)
181
frame_name = frame.f_globals.get('__name__', '<unknown>')
182
frame_lineno = frame.f_lineno
183
this = stack_add(extra+_repr_regexp(args[0]), frame_name, frame_lineno)
187
# Measure the compile time
188
comp = _real_compile(*args, **kwargs)
190
tcompile = _timer() - tstart
191
stack_finish(this, tcompile)
197
"""Install the hooks for measuring import and regex compile time."""
198
__builtins__['__import__'] = timed_import
199
re._compile = timed_compile
203
"""Remove the import and regex compile timing hooks."""
204
__builtins__['__import__'] = _real_import
205
re._compile = _real_compile