Skip to content

Commit 9e62b84

Browse files
committed
Merge pull request QuantEcon#83 from albop/timing
ENH: added tic, tac, toc functions
2 parents f23a4b5 + c4d2ea0 commit 9e62b84

File tree

2 files changed

+113
-0
lines changed

2 files changed

+113
-0
lines changed

quantecon/tests/test_timing.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
Filename: timing.py
3+
Authors: Pablo Winant
4+
Tests for timing.py
5+
"""
6+
7+
def test_tic_tac_toc():
8+
9+
from ..timing import tic, tac, toc
10+
import time
11+
12+
h = 0.1
13+
14+
tic()
15+
16+
time.sleep(h)
17+
el1 = tac()
18+
19+
time.sleep(h)
20+
el2 = tac()
21+
22+
time.sleep(h)
23+
el3 = toc()
24+
25+
assert(abs(el1-h)<0.01)
26+
assert(abs(el2-h)<0.01)
27+
assert(abs(el3-h*3)<0.01)
28+
29+
30+
if __name__ == "__main__":
31+
32+
test_tic_tac_toc()

quantecon/timing.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
"""
2+
Filename: timing.py
3+
Authors: Pablo Winant
4+
Date: 10/16/14
5+
Provides Matlab-like tic, tac and toc functions.
6+
"""
7+
8+
class __Timer__:
9+
'''Computes elapsed time, between tic, tac, and toc.
10+
11+
Methods
12+
-------
13+
tic :
14+
Resets timer.
15+
toc :
16+
Returns and prints time elapsed since last tic().
17+
tac :
18+
Returns and prints time elapsed since last
19+
tic(), tac() or toc() whichever occured last.
20+
'''
21+
22+
start = None
23+
last = None
24+
25+
def tic(self):
26+
"""Resets timer."""
27+
28+
29+
import time
30+
31+
t = time.time()
32+
self.start = t
33+
self.last = t
34+
35+
36+
def tac(self):
37+
"""Returns and prints time elapsed since last tic()"""
38+
39+
import time
40+
41+
if self.start is None:
42+
raise Exception("tac() without tic()")
43+
44+
t = time.time()
45+
elapsed = t-self.last
46+
self.last = t
47+
48+
print("TAC: Elapsed: {} seconds.".format(elapsed))
49+
return elapsed
50+
51+
52+
def toc(self):
53+
"""Returns and prints time elapsed since last
54+
tic() or tac() whichever occured last"""
55+
56+
import time
57+
58+
if self.start is None:
59+
raise Exception("toc() without tic()")
60+
61+
t = time.time()
62+
self.last = t
63+
elapsed = t-self.start
64+
65+
66+
print("TOC: Elapsed: {} seconds.".format(elapsed))
67+
return elapsed
68+
69+
__timer__ = __Timer__()
70+
71+
def tic():
72+
"""Saves time for future use with tac or toc."""
73+
return __timer__.tic()
74+
75+
def tac():
76+
"""Prints and returns elapsed time since last tic, tac or toc."""
77+
return __timer__.tac()
78+
79+
def toc():
80+
"""Prints and returns elapsed time since last tic, tac or toc."""
81+
return __timer__.toc()

0 commit comments

Comments
 (0)