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?
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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With