forked from basho/riak-python-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark.py
More file actions
168 lines (138 loc) · 4.56 KB
/
benchmark.py
File metadata and controls
168 lines (138 loc) · 4.56 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
"""
Copyright 2013 Basho Technologies, Inc.
This file is provided to you under the Apache License,
Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
"""
import os
import gc
__all__ = ['measure', 'measure_with_rehearsal']
def measure_with_rehearsal():
"""
Runs a benchmark when used as an iterator, injecting a garbage
collection between iterations. Example:
for b in benchmark.measure_with_rehearsal():
with b.report("pow"):
for _ in range(10000):
math.pow(2,10000)
with b.report("factorial"):
for i in range(100):
math.factorial(i)
"""
return Benchmark(True)
def measure():
"""
Runs a benchmark once when used as a context manager. Example:
with benchmark.measure() as b:
with b.report("pow"):
for _ in range(10000):
math.pow(2,10000)
with b.report("factorial"):
for i in range(100):
math.factorial(i)
"""
return Benchmark()
class Benchmark(object):
"""
A benchmarking run, which may consist of multiple steps. See
measure_with_rehearsal() and measure() for examples.
"""
def __init__(self, rehearse=False):
"""
Creates a new benchmark reporter.
:param rehearse: whether to run twice to take counter the effects
of garbage collection
:type rehearse: boolean
"""
self.rehearse = rehearse
if rehearse:
self.count = 2
else:
self.count = 1
self._report = None
def __enter__(self):
if self.rehearse:
raise ValueError("measure_with_rehearsal() cannot be used in with "
"statements, use measure() or the for..in "
"statement")
print_header()
self._report = BenchmarkReport()
self._report.__enter__()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if self._report:
return self._report.__exit__(exc_type, exc_val, exc_tb)
else:
print
return True
def __iter__(self):
return self
def next(self):
"""
Runs the next iteration of the benchmark.
"""
if self.count == 0:
raise StopIteration
elif self.count > 1:
print_rehearsal_header()
else:
if self.rehearse:
gc.collect()
print ("-" * 59)
print
print_header()
self.count -= 1
return self
def report(self, name):
"""
Returns a report for the current step of the benchmark.
"""
self._report = None
return BenchmarkReport(name)
def print_rehearsal_header():
"""
Prints the header for the rehearsal phase of a benchmark.
"""
print
print "Rehearsal -------------------------------------------------"
def print_report(label, user, system, real):
"""
Prints the report of one step of a benchmark.
"""
print "{:<12s} {:12f} {:12f} ( {:12f} )".format(label, user, system, real)
def print_header():
"""
Prints the header for the normal phase of a benchmark.
"""
print "{:<12s} {:<12s} {:<12s} ( {:<12s} )"\
.format('', 'user', 'system', 'real')
class BenchmarkReport(object):
"""
A labeled step in a benchmark. Acts as a context-manager, printing
its timing results when the context exits.
"""
def __init__(self, name='benchmark'):
self.name = name
self.start = None
def __enter__(self):
self.start = os.times()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if not exc_type:
user1, system1, _, _, real1 = self.start
user2, system2, _, _, real2 = os.times()
print_report(self.name, user2 - user1, system2 - system1,
real2 - real1)
elif exc_type is KeyboardInterrupt:
return False
else:
print "EXCEPTION! %r" % ((exc_type, exc_val, exc_tb),)
return True