【问题标题】:Dealing with microseconds处理微秒
【发布时间】:2022-01-25 01:28:57
【问题描述】:

我已经编写了这段代码,我希望该代码能够在瞬间准确运行。但是,每次迭代都需要几毫秒,这会导致我的程序出现一点延迟。有没有一种方法可以像减去秒一样减去这些毫秒。

import pandas as pd
import datetime as dt
import time

while True:
    now = dt.datetime.now()
    current_time = now.strftime('%Y-%m-%d %H:%M:%S')
    seconds = int(current_time[-2:])
    sleep_sec = 60 - seconds
    time.sleep(sleep_sec)
    print(dt.datetime.now())

这是输出:

从输出中可以看出,每次迭代都会增加几毫秒的时间。我想要的是打印毫秒也为零的确切分钟。

【问题讨论】:

  • 你基本上不能,因为你不是唯一使用计算机的进程
  • @MadPhysicist 我可以像减去秒一样减去这些毫秒吗??
  • 否,因为您对睡眠结束时间的控制没有足够的分辨率。时钟有足够的分辨率,但你不能保证你的进程有一个时间段,除非你把它的好数字改成一些荒谬的东西,此时你几乎冻结了系统。

标签: python datetime


【解决方案1】:

time.sleep 如果您想睡几秒钟,则接受浮点数。话虽这么说,我不希望 python 能够做到精确的毫秒精度(通常在你的系统中发生的事情太多了,对于这种精度级别)。

【讨论】:

    【解决方案2】:

    使用 time.time() 代替 time.sleep()

    import time
    import datetime as dt
    start_time = time.time()
    
    while True:
        if time.time() - start_time > 60:
            # if 60 seconds pass do something
            print(dt.datetime.now())
            start_time = time.time()
            print("60 seconds passed")
    

    输出:

    2021-12-24 12:48:30.542806
    60 seconds passed
    2021-12-24 12:49:30.543792
    60 seconds passed
    2021-12-24 12:50:30.544508
    60 seconds passed
    2021-12-24 12:51:30.544826
    60 seconds passed
    2021-12-24 12:52:30.545028
    60 seconds passed
    2021-12-24 12:53:30.545661
    60 seconds passed
    2021-12-24 12:54:30.546452
    60 seconds passed
    

    仍有偏移,但不如您的输出那么重要

    【讨论】:

      【解决方案3】:

      使用线程,代码速度很快,并且准确地在一分钟开始执行。

      def create_candle():
          candle_timeframe = 60 # seconds
          current_sec = dt.datetime.now().second
          sleep_sec = candle_timeframe - current_sec
          print(dt.datetime.now())
          threading.Timer(sleep_sec, create_candle).start()
      
      candle_timeframe = 60 # seconds
      current_sec = dt.datetime.now().second
      sleep_sec = candle_timeframe - current_sec
      threading.Timer(sleep_sec, create_candle).start()
      

      【讨论】:

        猜你喜欢
        • 2017-06-12
        • 1970-01-01
        • 1970-01-01
        • 2011-04-18
        • 1970-01-01
        • 1970-01-01
        • 2015-09-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多