【问题标题】:python - loop at exact time intervalspython - 以确切的时间间隔循环
【发布时间】:2017-12-26 13:16:10
【问题描述】:

我想以精确的时间间隔(大约 15 秒)运行一段代码 最初我使用 time.sleep(),但问题是代码需要一秒钟左右才能运行,所以它会不同步。

我写了这个,我觉得很不整洁,因为我不喜欢使用 while 循环。有没有更好的办法?

import datetime as dt
import numpy as np

iterations = 100
tstep = dt.timedelta(seconds=5)
for i in np.arange(iterations):
    startTime = dt.datetime.now()
    myfunction(doesloadsofcoolthings)
    while dt.datetime.now() < startTime + tstep:
        1==1

【问题讨论】:

    标签: python-3.x time


    【解决方案1】:

    理想情况下,人们会使用线程来完成此任务。你可以做类似的事情

    import threading
    interval = 15
    
    def myPeriodicFunction():
        print "This loops on a timer every %d seconds" % interval
    
    def startTimer():
        threading.Timer(interval, startTimer).start()
        myPeriodicFunction()
    

    然后你就可以打电话了

    startTimer()
    

    为了启动循环计时器。

    【讨论】:

    • 这是否意味着如果该进程仍在运行,它会在不同的cpu线程上启动下一个进程?
    • 这不准确。我在每个循环中都经历了大约 0.01 秒的变化。我的周期性函数只是 print(datetime.now())
    【解决方案2】:

    您可以使用简单的 bash 行:

    watch -n 15m python yourcode.py
    

    【讨论】:

      【解决方案3】:

      考虑跟踪代码运行所花费的时间(timer() 函数),然后在完成后休眠 15 - exec_time 秒。

      start = datetime.now()
      do_many_important_things()
      end = datetime.now()
      
      exec_time = end - start
      time.sleep(15-exec_time.total_seconds())
      

      【讨论】:

        猜你喜欢
        • 2018-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-26
        • 1970-01-01
        相关资源
        最近更新 更多