-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontexttimer.py
55 lines (34 loc) · 1.07 KB
/
contexttimer.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
""" Using the with keyword to time code snippets. """
from contextlib import contextmanager
import time
import sys
# @contextmanager
# def ContextTimer(name="Unknown", outf=sys.stdout):
# t0 = time.time()
# outf.write("[%s ..." % name)
# outf.flush()
# yield
# t1 = time.time()
# outf.write(" completed (%f seconds)]\n" % (t1 - t0))
class ContextTimer(object):
def __init__(self, name="Unknown", outf=sys.stdout):
self.name = name
self.outf = outf
def __enter__(self):
if self.outf is not None:
self.outf.write("[%s ..." % self.name)
self.outf.flush()
self.t0 = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.t1 = time.time()
self.duration = self.t1 - self.t0
self.outf.write(" completed (%f seconds)]\n" % self.duration)
def main():
with ContextTimer("Long loop") as ct:
s = 0
for i in xrange(10000000):
s += i
print s, ct.duration
if __name__ == '__main__':
main()