-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add function to get running time of a function
- Loading branch information
1 parent
fce9866
commit e8e45e3
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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)) |