1
2import time
3import who_calls
4import neo_cgi
5
6PROFILER_DATA = []
7PROFILER_START = 0
8PROFILER_ENABLED = 0
9PROFILER_DEPTH = 0
10
11def enable():
12    global PROFILER_START
13    global PROFILER_ENABLED
14    global PROFILER_DATA
15    PROFILER_START = time.time()
16    PROFILER_ENABLED = 1
17    PROFILER_DATA = []
18
19def disable():
20    global PROFILER_START
21    global PROFILER_ENABLED
22    global PROFILER_DATA
23    PROFILER_START = 0
24    PROFILER_ENABLED = 0
25    PROFILER_DATA = []
26
27def hdfExport(prefix, hdf):
28    global PROFILER_DATA
29    n = 0
30    for p in PROFILER_DATA:
31        hdf.setValue("%s.%d.when" % (prefix, n), "%5.2f" % (p.when))
32        hdf.setValue("%s.%d.time" % (prefix, n), "%5.2f" % (p.length))
33        hdf.setValue("%s.%d.klass" % (prefix, n), p.klass)
34        hdf.setValue("%s.%d.what" % (prefix, n), " " * p.depth + p.what)
35        hdf.setValue("%s.%d.where" % (prefix, n), neo_cgi.htmlEscape(p.where))
36
37class Profiler:
38    def __init__ (self, klass, what):
39        global PROFILER_START
40        global PROFILER_ENABLED
41        global PROFILER_DATA
42        global PROFILER_DEPTH
43        if not PROFILER_ENABLED: return
44        self.when = time.time() - PROFILER_START
45        self.klass = klass
46        self.where = who_calls.pretty_who_calls()
47        self.what = what
48        self.length = 0
49        self.depth = PROFILER_DEPTH
50        PROFILER_DEPTH = PROFILER_DEPTH + 1
51
52        PROFILER_DATA.append(self)
53
54    def end(self):
55        global PROFILER_ENABLED
56        global PROFILER_DEPTH
57        if not PROFILER_ENABLED: return
58        self.length = time.time() - self.when - PROFILER_START
59        PROFILER_DEPTH = PROFILER_DEPTH - 1
60        if PROFILER_DEPTH < 0: PROFILER_DEPTH = 0
61
62class ProfilerCursor:
63    def __init__ (self, real_cursor):
64        self.real_cursor = real_cursor
65
66    def execute (self, query, args=None):
67        p = Profiler("SQL", query)
68        r = self.real_cursor.execute(query, args)
69        p.end()
70        return r
71
72    def __getattr__ (self, key):
73        return getattr(self.real_cursor, key)
74