【问题标题】:Make a loop last once second using datetime?使用日期时间进行最后一次循环?
【发布时间】:2018-12-01 03:53:13
【问题描述】:

Stackoverflow 的聪明头脑,我有一个任务要找你。 目前我正在运行一个循环,其中发生计算和数据采集。随着时间的推移,这些变得越来越复杂。我希望循环的每次运行都持续一秒钟。由于计算时间的增长,最后一个简单的“sleep(1)”并没有真正的帮助。

while True:

    #here calculations happen that take more and more time

    print 'some of the data'

    sleep(1)

我希望在这些计算之前和之后使用 datetime 来计算秒/毫秒,然后将差异输入到 sleep 命令中。但我无法完全理解它。谁能帮帮我?

    a=datetime.now()
    #calculations
    b=datetime.now()
    calctime=(b-a).total_seconds()
    sleep(1-calctime)

【问题讨论】:

  • 你可能会发现一些有用的信息here
  • 既然total_seconds()等价于time / timedelta(seconds=1),难道sleep(1 * calctime)不应该做吗?
  • 不,我想在循环计算所需的时间之前减少睡眠时间,即一秒。因为计算的增长时间使得循环持续一秒 + calctime。

标签: python loops datetime sleep


【解决方案1】:

试试这个:

from datetime import datetime
import time
def test():
    a = datetime.now()
    # calculations
    b = datetime.now()
    calctime = (b - a).total_seconds()
    print("one")
    time.sleep((1 - calctime) if (1-calctime)>0.0 else 0) #if your calculation already took 1 or more than 1 second then then make the waiting time 0
    print("two")

test()

【讨论】:

  • 你把它带到了一个新的水平。谢谢。我自己已经解决了,但我可能会在 1 秒内使用您的加法进行计算。
  • 这是我的荣幸 :)
【解决方案2】:
  a=datetime.now()
  #calculations
  b=datetime.now()
  calctime=b-a
  ms = calctime.microseconds
  if calctime.seconds == 0:
      sleep(1-ms/1000000)

更多信息:Python speed testing - Time Difference - milliseconds

【讨论】:

    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 2013-05-28
    • 2023-03-25
    相关资源
    最近更新 更多