如何为循环计时?

2024-04-30 01:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,其中我有一个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')

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


Tags: 代码importtruefortime时间not解决方案