Skip to content

Commit

Permalink
Add function to get running time of a function
Browse files Browse the repository at this point in the history
  • Loading branch information
paniabhisek committed May 25, 2020
1 parent fce9866 commit e8e45e3
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions timer.py
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))

0 comments on commit e8e45e3

Please sign in to comment.