【问题标题】:waiting time which excludes time taken by the program等待时间,不包括程序花费的时间
【发布时间】:2021-12-15 17:14:51
【问题描述】:

我正在尝试模拟客户端实时发送数据。数据是数据帧的行,由数据帧每行之间经过的时间量索引。我有

for index, row in df.iterrows():
    time.sleep(index)
    sender(client, row)

其中 sender 是向服务器发送内容的函数;

def sender(socket, msg):
    message = pickle.dumps(msg) # encodes messages into bytes, so it can be sent
    msg_length = len(message)
    send_length = pickle.dumps(str(msg_length))
    msg = bytes('{:<64}'.format(msg_length),FORMAT)+message
    socket.send(msg)

但是由于程序需要几毫秒来实际发送消息并进行一些其他计算,它开始偏离其发送数据的正确时间;程序复合的时间。

考虑到程序不是即时的,我怎样才能让它等待正确的时间?

我试过了:

delay = timedelta(0)
start = datetime.now()
for index, row in df.iterrows():
    delay += timedelta(seconds=index*60*24*60/60)
    while datetime.now() < start + delay:
        pass
        
    sender(client, row)

但它不起作用,不知道为什么

【问题讨论】:

    标签: python pandas time sleep


    【解决方案1】:

    可以使用python的sleep功能:

    import time
    
    def print_hello_after_60_milliseconds():
         time.sleep(0.06)
         print('hello')
        
    print_hello_after_60_milliseconds() 
    

    def print_hello_after_3_seconds():
         time.sleep(3)
         print('hello')
        
    print_hello_after_3_seconds()  
    

    500 毫秒是 time.sleep(0.5)。但是这个解决方案只有在你想等待固定的时间时才有用,我不知道你是否想根据条件动态等待。

    【讨论】:

    • 感谢您的回复,我尝试使用睡眠时间,但程序时间复合后会推迟它
    猜你喜欢
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多