Measuring the time it takes to start and end a function in Python

In Python 3.4.1, I am trying to measure how long it takes to start and end a function and then write. I am doing it like this:

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

This usually causes Python to spit out something around 6.29989986222767E-06 (or 0.00000629989986222767E). Then I tried this with time.sleep:

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

This again led to 6.87261802845284E-06, although (at least I think) it will take 3 seconds. I tried this with threads, with the same result. What do you think? How can I determine how long it takes to start and end a function?

+5
source share
3 answers

I usually use this decorator to perform 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 a more accurate time for tests than time.clock() , primarily because time.clock() measures the processor time. time.time() will return the seconds elapsed from the era (i.e. the wall time) that you need.

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

+2
source

For a quick performance analysis, I use the following two lines (plus import):

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

It is short, simple and all that I usually need.

(In most cases, I imported numpy anyway. Therefore, there is no overhead for me.)

+1
source

I admit that I'm not very good at Python asyncio, but I believe that the problem is not in your timeline, but in using asyncio .

I think that you are just creating the future with the value of the method (), however this is all you need: actually making this promise.

You do not take into account the actual estimate of future value. This is why sleep time (3) and method () take about the same amount of time.

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

0
source

Source: https://habr.com/ru/post/1200538/


All Articles