Albert Hopkins wrote:
On Fri, 2010-07-30 at 14:28 +0200, Hrvoje Niksic wrote:
Steven D'Aprano <st...@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.

That won't work very well for functions which don't run for long. You
could fix that by adding a counter for the number of times it's run and
the total time.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to