-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtimer.py
42 lines (31 loc) · 1.29 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
# This script has been taken from "Learning Python(5th edition) by Mark Lutz"
"""
:py:func:`total(spam, 1, 2, a=3, b=4, _reps=1000)` calls and times :py:func:`spam(1, 2, a=3, b=4)`
_reps times, and returns total time for all runs, with final result.
:py:func:`bestof(spam, 1, 2, a=3, b=4, _reps=5)` runs best-of-N timer to attempt to filter
out system load variation, and returns best time among _reps tests.
:py:func:`bestoftotal(spam, 1, 2, a=3, b=4, _reps1=5, reps=1000)` runs best-of-totals test,
which takes the best among _reps1 runs of (the total of _reps runs);
"""
import time, sys
timer = time.clock if sys.platform[:3] == 'win' else time.time
def total(func, *pargs, **kargs):
_reps = kargs.pop('_reps', 1000)
repslist = list(range(_reps))
start = timer()
for i in repslist:
ret = func(*pargs, **kargs)
elapsed = timer() - start
return (elapsed, ret)
def bestof(func, *pargs, **kargs):
_reps = kargs.pop('_reps', 5)
best = 2 ** 32
for i in range(_reps):
start = timer()
ret = func(*pargs, **kargs)
elapsed = timer() - start
if elapsed < best: best = elapsed
return (best, ret)
def bestoftotal(func, *pargs, **kargs):
_reps1 = kargs.pop('_reps1', 5)
return min(total(func, *pargs, **kargs) for i in range(_reps1))