Created
April 26, 2010 11:18
-
-
Save simonw/379216 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Simple timer class. Example usage: | |
t = Timer() | |
for url in ('http://www.google.com/', 'http://www.yahoo.com/'): | |
t.start('fetch url') | |
content = urllib.urlopen(url).read() | |
t.stop('fetch url') | |
t.start('reorder bytes') | |
bytes = list(content) | |
bytes.sort() | |
t.stop('reorder bytes') | |
t.print_summary() | |
fetch url: 2 calls, avg = 0.557923, min = 0.547084, max = 0.568763, sum = 1.115847 | |
reorder bytes: 2 calls, avg = 0.028007, min = 0.003244, max = 0.052770, sum = 0.056014 | |
""" | |
import time | |
class Timer(object): | |
def __init__(self): | |
self.in_flight = {} | |
self.results = {} | |
def start(self, name): | |
assert name not in self.in_flight,\ | |
"Can't start a '%s' timer if one is already running" % name | |
self.in_flight[name] = time.time() | |
def stop(self, name): | |
assert name in self.in_flight,\ | |
"Can't stop a '%s' timer without starting it first" % name | |
duration = time.time() - self.in_flight[name] | |
del self.in_flight[name] | |
self.results.setdefault(name, []).append(duration) | |
def summary(self, name): | |
results = self.results.get(name, []) | |
s = '%s: %d calls, avg = %.6f, min = %.6f, max = %.6f, sum = %.6f' % ( | |
name, len(results), sum(results) / len(results), | |
min(results), max(results), sum(results) | |
) | |
return s | |
def print_summary(self): | |
for key in self.results: | |
print self.summary(key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment