/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to profile_imports.py

  • Committer: John Arbash Meinel
  • Date: 2010-02-10 21:36:32 UTC
  • mto: This revision was merged to the branch mainline in revision 5024.
  • Revision ID: john@arbash-meinel.com-20100210213632-cb6oxouuiyl91rju
Fix bug #304182 by adding a trivial docstring to Tree.iter_changes

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2008, 2009, 2010 by Canonical Ltd
 
2
# Written by John Arbash Meinel <john@arbash-meinel.com>
 
3
#
 
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.
 
8
#
 
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.
 
13
#
 
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
 
17
 
 
18
"""A custom importer and regex compiler which logs time spent."""
 
19
 
 
20
import sys
 
21
import time
 
22
 
 
23
 
 
24
if sys.version_info < (2, 5, 0):
 
25
    import sre
 
26
    re = sre
 
27
else:
 
28
    import re
 
29
 
 
30
 
 
31
_parent_stack = []
 
32
_total_stack = {}
 
33
_info = {}
 
34
_cur_id = 0
 
35
_timer = time.time
 
36
if sys.platform == 'win32':
 
37
    _timer = time.clock
 
38
 
 
39
 
 
40
def stack_add(name, frame_name, frame_lineno, scope_name=None):
 
41
    """Start a new record on the stack"""
 
42
    global _cur_id
 
43
    _cur_id += 1
 
44
    this_stack = (_cur_id, name)
 
45
 
 
46
    if _parent_stack:
 
47
        _total_stack[_parent_stack[-1]].append(this_stack)
 
48
    _total_stack[this_stack] = []
 
49
    _parent_stack.append(this_stack)
 
50
    _info[this_stack] = [len(_parent_stack)-1, frame_name, frame_lineno, scope_name]
 
51
 
 
52
    return this_stack
 
53
 
 
54
 
 
55
def stack_finish(this, cost):
 
56
    """Finish a given entry, and record its cost in time"""
 
57
    global _parent_stack
 
58
 
 
59
    assert _parent_stack[-1] == this, \
 
60
        'import stack does not end with this %s: %s' % (this, _parent_stack)
 
61
    _parent_stack.pop()
 
62
    _info[this].append(cost)
 
63
 
 
64
 
 
65
def log_stack_info(out_file, sorted=True, hide_fast=True):
 
66
    # Find all of the roots with import = 0
 
67
    out_file.write(' cum  inline name\t\t\t\t\t\tframe\n')
 
68
    todo = [(value[-1], key) for key,value in _info.iteritems() if value[0] == 0]
 
69
 
 
70
    if sorted:
 
71
        todo.sort()
 
72
 
 
73
    while todo:
 
74
        cum_time, cur = todo.pop()
 
75
        children = _total_stack[cur]
 
76
 
 
77
        c_times = []
 
78
 
 
79
        info = _info[cur]
 
80
        if hide_fast and info[-1] < 0.0001:
 
81
            continue
 
82
 
 
83
        # Compute the module time by removing the children times
 
84
        mod_time = info[-1]
 
85
        for child in children:
 
86
            c_info = _info[child]
 
87
            mod_time -= c_info[-1]
 
88
            c_times.append((c_info[-1], child))
 
89
 
 
90
        # indent, cum_time, mod_time, name,
 
91
        # scope_name, frame_name, frame_lineno
 
92
        out_file.write('%5.1f %5.1f %s %-35s\t@ %s:%d\n'
 
93
            % (info[-1]*1000., mod_time*1000., '+'*info[0], 
 
94
               cur[1][:35], info[1], info[2]))
 
95
 
 
96
        if sorted:
 
97
            c_times.sort()
 
98
        else:
 
99
            c_times.reverse()
 
100
        todo.extend(c_times)
 
101
 
 
102
 
 
103
_real_import = __import__
 
104
 
 
105
def timed_import(name, globals, locals, fromlist, level=None):
 
106
    """Wrap around standard importer to log import time"""
 
107
    # level is only passed by python2.6
 
108
 
 
109
    scope_name = globals.get('__name__', None)
 
110
    if scope_name is None:
 
111
        scope_name = globals.get('__file__', None)
 
112
    if scope_name is None:
 
113
        scope_name = globals.keys()
 
114
    else:
 
115
        # Trim out paths before bzrlib
 
116
        loc = scope_name.find('bzrlib')
 
117
        if loc != -1:
 
118
            scope_name = scope_name[loc:]
 
119
        # For stdlib, trim out early paths
 
120
        loc = scope_name.find('python2.4')
 
121
        if loc != -1:
 
122
            scope_name = scope_name[loc:]
 
123
 
 
124
    # Figure out the frame that is doing the importing
 
125
    frame = sys._getframe(1)
 
126
    frame_name = frame.f_globals.get('__name__', '<unknown>')
 
127
    extra = ''
 
128
    if frame_name.endswith('demandload'):
 
129
        # If this was demandloaded, we have 3 frames to ignore
 
130
        extra = '(demandload) '
 
131
        frame = sys._getframe(4)
 
132
        frame_name = frame.f_globals.get('__name__', '<unknown>')
 
133
    elif frame_name.endswith('lazy_import'):
 
134
        # If this was lazily imported, we have 3 frames to ignore
 
135
        extra = '[l] '
 
136
        frame = sys._getframe(4)
 
137
        frame_name = frame.f_globals.get('__name__', '<unknown>')
 
138
    if fromlist:
 
139
        extra += ' [%s]' % (', '.join(map(str, fromlist)),)
 
140
    frame_lineno = frame.f_lineno
 
141
 
 
142
    this = stack_add(extra + name, frame_name, frame_lineno, scope_name)
 
143
 
 
144
    tstart = _timer()
 
145
    try:
 
146
        # Do the import
 
147
        mod = _real_import(name, globals, locals, fromlist)
 
148
    finally:
 
149
        tload = _timer()-tstart
 
150
        stack_finish(this, tload)
 
151
 
 
152
    return mod
 
153
 
 
154
 
 
155
_real_compile = re._compile
 
156
 
 
157
 
 
158
def timed_compile(*args, **kwargs):
 
159
    """Log how long it takes to compile a regex"""
 
160
 
 
161
    # And who is requesting this?
 
162
    frame = sys._getframe(2)
 
163
    frame_name = frame.f_globals.get('__name__', '<unknown>')
 
164
 
 
165
    extra = ''
 
166
    if frame_name.endswith('lazy_regex'):
 
167
        # If this was lazily compiled, we have 3 more frames to ignore
 
168
        extra = '[l] '
 
169
        frame = sys._getframe(5)
 
170
        frame_name = frame.f_globals.get('__name__', '<unknown>')
 
171
    frame_lineno = frame.f_lineno
 
172
    this = stack_add(extra+repr(args[0]), frame_name, frame_lineno)
 
173
 
 
174
    tstart = _timer()
 
175
    try:
 
176
        # Measure the compile time
 
177
        comp = _real_compile(*args, **kwargs)
 
178
    finally:
 
179
        tcompile = _timer() - tstart
 
180
        stack_finish(this, tcompile)
 
181
 
 
182
    return comp
 
183
 
 
184
 
 
185
def install():
 
186
    """Install the hooks for measuring import and regex compile time."""
 
187
    __builtins__['__import__'] = timed_import
 
188
    re._compile = timed_compile
 
189
 
 
190
 
 
191
def uninstall():
 
192
    """Remove the import and regex compile timing hooks."""
 
193
    __builtins__['__import__'] = _real_import
 
194
    re._compile = _real_compile
 
195