首页 > 解决方案 > Python“for循环”循环时间限制

问题描述

如何为“for循环”设置时间限制?

说我想要每 200 毫米循环一次

for data in online_database:
    looping time  = 200 mms
    print(data)

谢谢!

标签: pythonloopsfor-loop

解决方案


也许这样的事情可以帮助

import time

for i in YourSequence:

    current_millis = round(time.monotonic() * 1000)
    max_milis = (current_millis + 200) #200 is for the time difference

    while round(time.monotonic() * 1000) < max_milis:
          #----Your code------

此外,如果您的程序很大,您可以添加这些行以定期留意您的程序是否超过了最大时间限制

if round(time.monotonic() * 1000) > max_milis:
       break

像这样的东西

import time

for i in a:

    current_millis = round(time.monotonic() * 1000)
    max_milis = (current_millis  + 200)

    while round(time.monotonic() * 1000) < max_milis:

        #Your Codes......

        if round(time.monotonic() * 1000) > max_milis:
              break

        #Your Codes......

        if round(time.monotonic() * 1000) > max_milis:
             break       

        #Your Codes......
        break

推荐阅读