Xanco
Xanco

Reputation: 902

Measuring the time it takes for a function to run and complete in Python

In Python 3.4.1, I'm trying to measure how long it takes for a function to run and complete then recording it. I'm currently doing it this like so:

starttime = time.clock()
asyncio.wait_for((method()), 5)
endtime = time.clock()
print(endtime - starttime)

This usually results in Python spitting out something around 6.29989986222767E-06 (or 0.00000629989986222767E). Then I tried it with a time.sleep:

starttime = time.clock()
asyncio.wait_for((time.sleep(3)), 5)
endtime = time.clock()
print(endtime - starttime)

This again resulted in 6.87261802845284E-06, even though (at least I think) it should take 3 seconds. I have tried this using threads, with the same result. What do you think? How can I measure how long it takes for a function to run and complete?

Upvotes: 6

Views: 6561

Answers (3)

SVatasoiu
SVatasoiu

Reputation: 171

I'll admit that I'm not very familiar with Python's asyncio, but I believe the issue is not in your timing, but in your useage of asyncio.

I think you are just creating a future with the value of method(), however that is all that you are timing: the actual creation of this promise.

You are not timing the actual evaluation of the future value. This is why timing sleep(3) and method() take roughly the same amount of time.

I suggest trying to change asyncio.wait_for((method()), 5) with yield from asyncio.wait_for((method()), 3) or just timing method() if you can.

Upvotes: 1

Falko
Falko

Reputation: 17877

For quick performance analyses I use the following two lines (plus imports):

import time
import numpy as np

t = time.time()
# ...
print np.round_(time.time() - t, 3), 'sec elapsed'

It's short, simple and all I usually need.

(In most cases I've imported numpy anyway. So thats no overhead for me.)

Upvotes: 2

zengr
zengr

Reputation: 38899

I generally use this decorator to time my functions:

import time                                                
def timeit(method):
    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()
        print '%r (%r, %r) %2.2f sec' % \
              (method.__name__, args, kw, te-ts)
        return result

    return timed

@timeit
def timeme():
    time.sleep(3)

time.time() gives more precise time for benchmarks than time.clock() primarily because time.clock() measures CPU time. time.time() will return seconds passed since epoch (i.e. wall time), which is what you need.

Or you can also use timeit https://docs.python.org/3/library/timeit.html

Upvotes: 2

Related Questions