-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.py
76 lines (63 loc) · 2.37 KB
/
timer.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Timer for checking speed of code block.
Wrap blocks of code that you want to time with Python's with keyword and this Timer context manager. It will take care
of starting the timer when your code block begins execution and stopping the timer when your code block ends.
Adapted from: http://www.huyng.com/posts/python-performance-analysis/ (Mar 19, 2015)
=== Example ===
from timer import Timer
from redis import Redis
rdb = Redis()
with Timer() as t:
rdb.lpush("foo", "bar")
print "=> elasped lpush: %s s" % t.secs
with Timer() as t:
rdb.lpop("foo")
print "=> elasped lpop: %s s" % t.secs
"""
import time
__author__ = 'Marc Schulder'
class Timer(object):
"""
Timer for checking speed of code block.
Wrap blocks of code that you want to time with Python's with keyword and this Timer context manager. It will take care
of starting the timer when your code block begins execution and stopping the timer when your code block ends.
"""
def __init__(self, info=None, verbose=False):
self.verbose = verbose
self.info = info
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *_):
self.end = time.time()
self.secs = self.end - self.start
self.msecs = self.secs * 1000 # milliseconds
if self.verbose:
print self.getSummary(self.info)
def getSummary(self, info=None):
if info is None:
info = self.info
if info is None:
return 'Elapsed time: %s' % getTimeString(self.secs)
else:
return '%s %s' % (info, getTimeString(self.secs))
def getTimeString(seconds):
"""
Get a pretty time string, using hours, minutes, seconds and milliseconds as required.
:param seconds: The desired time span, given in seconds. Can be an int or a float.
:return: A string representing the desired time span, given in hours, minutes, seconds and milliseconds.
"""
units = list()
msecs = (seconds % 1) * 1000
if msecs >= 1:
units.append('{0}ms'.format(int(msecs % 60)))
units.append('{0}s'.format(int(seconds % 60)))
minutes = seconds/60
if minutes >= 1:
units.append('{0}m'.format(int(minutes % 60)))
hours = minutes/60
if hours >= 1:
units.append('{0}h'.format(int(hours % 60)))
return ' '.join(units[::-1])