Python“for循环”循环时间限制

问题描述 投票:0回答:3

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

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

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

谢谢!

python loops for-loop
3个回答
0
投票
import time

t_sleep = 0.2

for x in range(10):
    print(x)
    time.sleep(t_sleep)

这段代码每次迭代都会休眠 0.2 秒


0
投票

也许这样的事情可以帮助

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

0
投票

您可以使用

default_timer
模块中的
timeit
来查找经过了多少时间:

from timeit import default_timer

start_time = default_timer()
looping_time = 0.2

for data in online_database:
    print(data)
    end_time = default_timer()
    if end_time - start_time > looping_time:
         break

注意:

default_timer()
返回从固定时间点开始的秒数。它专门用于计时。

文档:timeit.default_timer

© www.soinside.com 2019 - 2024. All rights reserved.