两个循环之间经过的时间

elapsed time between the two loops

我想测量两行代码之间的时间差(以秒为单位)。

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

我想减去(time_2) - (time_1)。但问题是 time_1 总是在变化,我无法计算时间。

您可以将值直接存储在数组中,并在每次向数组追加值时更改 time_1 值。它可能是这样的:

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()