forked from sbu-python-class/python-science
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofile.py
More file actions
109 lines (70 loc) · 2.27 KB
/
profile.py
File metadata and controls
109 lines (70 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"""
A very simple profiling class. Define some timers and methods
to start and stop them. Nesting of timers is tracked so we can
pretty print the profiling information.
# define a timer object, labeled 'my timer'
a = timer('my timer')
This will add 'my timer' to the list of keys in the 'my timer'
dictionary. Subsequent calls to the timer class constructor
will have no effect.
# start timing the 'my timer' block of code
a.begin()
... do stuff here ...
# end the timing of the 'my timer' block of code
a.end()
for best results, the block of code timed should be large
enough to offset the overhead of the timer class method
calls.
Multiple timers can be instanciated and nested. The stackCount
global parameter keeps count of the level of nesting, and the
timerNesting data structure stores the nesting level for each
defined timer.
timeReport() is called at the end to print out a summary of the
timing.
At present, no enforcement is done to ensure proper nesting.
"""
import time
timers = {}
# keep basic count of how nested we are in the timers, so we can do some
# pretty printing.
stackCount = 0
timerNesting = {}
timerOrder = []
class timer:
def __init__ (self, name):
global timers, stackCount, timerNesting, timerOrder
self.name = name
keys = timers.keys()
if name not in keys:
timers[name] = 0.0
self.startTime = 0.0
timerOrder.append(name)
timerNesting[name] = stackCount
def begin(self):
global stackCount
self.startTime = time.time()
stackCount += 1
def end(self):
global timers, stackCount
elapsedTime = time.time() - self.startTime
timers[self.name] += elapsedTime
stackCount -= 1
def timeReport():
global timers, timerOrder, timerNesting
spacing = ' '
for key in timerOrder:
print timerNesting[key]*spacing + key + ': ', timers[key]
if __name__ == "__main__":
a = timer('1')
a.begin()
time.sleep(10.)
a.end()
b = timer('2')
b.begin()
time.sleep(5.)
c = timer('3')
c.begin()
time.sleep(20.)
b.end()
c.end()
timeReport()