measuring a function time
Albert Hopkins
marduk at letterboxes.org
Fri Jul 30 10:20:19 EDT 2010
On Fri, 2010-07-30 at 14:28 +0200, Hrvoje Niksic wrote:
> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
>
> > On Thu, 29 Jul 2010 14:42:58 +0200, Matteo Landi wrote:
> >
> >> This should be enough
> >>
> >>>>>import time
> >>>>>tic = time.time()
> >>>>>function()
> >>>>>toc = time.time()
> >>>>>print toc - tic
> >
> > You're typing that in the interactive interpreter, which means the
> > timer is counting the seconds while you're typing subsequent
> > commands. At the very least, you need to put that code into a
> > function.
>
> Or, trivially improved as follows:
>
> >>> t0 = time.time(); function(); t1 = time.time()
> >>> print t1 - t0
I'll just throw this out. I sometimes use a decorator to keep track of
a functions execution times:
def timed_function(f):
"""Function decorator that records the execution time of a
function"""
import time
def funct(*args, **kwargs):
__starttime = time.time()
result = f(*args, **kwargs)
__endtime = time.time()
funct.runtime = __endtime - __starttime
return result
return funct
Then
>>> from goodies import timed_function
>>> from time import sleep
>>> @timed_function
... def test(n):
... sleep(n)
...
>>> test(4)
>>> test.runtime
4.003864049911499
Works for simple stuff anyway.
-a
More information about the Python-list
mailing list