如何为for循环计时?

问题描述 投票:1回答:1

我有一个代码,其中有一个for循环

我希望for循环在特定时间运行,然后停止或退出。我试图找到这样的解决方案:

import time
    **NOT HELPFUL for me**
    def stopwatch(seconds):
        start = time.time()
        time.clock()    
        elapsed = 0
        while elapsed < seconds:
            elapsed = time.time() - start 
            time.sleep(1)  

    stopwatch(20)

我的代码是这样的:

for a in list:

   if condition true:
     print('Condition True')
   else 
     print('not true')

所以,我只需要运行此循环几秒钟,然后停止即可。任何帮助,将不胜感激。

python for-loop time break
1个回答
3
投票

仅从当前时间减去开始时间(以秒为单位)

import time
start = time.time()
for a in list:
    if time.time()-start > maxTimeout:
        break
    print("condition true" if condition else "not true")
© www.soinside.com 2019 - 2024. All rights reserved.