-1

I wanted to find out the amount of time taken for a module or function to execute. I have used two methods mentioned below, but the time taken in each case is not the same for the same function. Why?

import time
from timeit import default_timer as timer

start=timer()
ret,thresh1 = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
end=timer()
print("Time Taken by Binary Thresh1 = {}".format(end-start))

e1=cv2.getTickCount()
ret,thresh1 = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
e2=cv2.getTickCount()
t=(e2-e1)/cv2.getTickFrequency()
print("Time Taken by Binary Thresh2 = {}".format(t))

Output

Time Taken by Binary Thresh1 = 0.00017630465444318233
Time Taken by Binary Thresh2 = 3.005609493620777e-05

Kindly let me what is the reason , or anything wrong in the code?

Timus
  • 10,974
  • 5
  • 14
  • 28
Shishira
  • 23
  • 4
  • Your computer may have had to do more on other tasks at one point. It is never guaranteed that a function runs in the same amount of time every time. It depends on the environment... – Ivonet Dec 11 '17 at 08:47
  • Please take a look here: https://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python – Duloren Dec 11 '17 at 08:51
  • I'm not sure how you can measure anything with that script, considering there are at least two syntax errors. – Dan Mašek Dec 11 '17 at 12:26
  • maybe the precision/resolution of the different timers? Maybe overhead? MAYBE memory allocation for thresh1 image only during the first threshold computation? Did you try to create a new variable for the 2nd threshold computation? – Micka Dec 11 '17 at 15:02

1 Answers1

0

This is likely a problem of trying to measure too little and then seeing an effect of your PC doing other things

It would be worth having a read through this SO post which may give you some background info.

As for measuring what you want to measure better I would suggest doing it 100 or 1000 times and measuring the total time. You can then work backwards to see how long each attempt took or create an average time.

Also see here for tips on profiling Python code.

GPPK
  • 6,546
  • 4
  • 32
  • 57