Search code examples
pythontimeelapsedtime

elapsed time between the two loops


I want to measure the time difference (inseconds) between two lines of code.

while ret:
    ret, image_np=cap.read()
    time_1
    for condition:
         if condition:
             time_2

I want to subtract (time_2) - (time_1). But the problem is that time_1 always changes and I can't calculate the time.


Solution

  • You could store the values directly in an array and change your time_1 value each time you append a value to the array. Here is what it could look like :

    from datetime import datetime
    
    time_1 = datetime.now()
    elapsed_time = []
    
    # In my example I loop from 0 to 9 and take the elapsed time
    # when the value is 0 or 5
    for i in range(10):
        if i in [0,5]:
            elapsed_time.append(datetime.now()-time_1)
            time_1 = datetime.now()