gpt4 book ai didi

python - 是否可以以特定速度发送数据(每秒 x 项)

转载 作者:太空宇宙 更新时间:2023-11-04 01:56:45 27 4
gpt4 key购买 nike

(只是想提一下,这是我的第一个问题,如果我做错了什么,我深表歉意)。我正在制作一个解析 CSV 文件并将其保存为列表的 Python 程序。但是,该程序需要用户输入他们希望将数据发送到服务器的速度。我将如何调节数据发送的速度(即 100 项/秒等)我正在使用 PyQt5 作为 GUI 前端和 CSV 模块来解析文件。出于测试目的,我将数据发送到 Python 脚本编写的另一个 CSV。

我试过 sleep 和日期和时间,但由于读/写数据不是即时的,所以不会是 x 项/1 秒。我真的找不到任何文档,但我觉得日期和时间仍然可行,尽管我真的不知道,因为我是初学者。

我希望程序读取 CSV 文件并以特定速率/秒将其写入/发送到另一个文件。我只让程序以正常速度编写它。

提前谢谢你。

最佳答案

正如@KlausD 所说,如果您想在发送之间进行处理,可以在线程中执行某些操作并使用队列。但是您可能只想在主线程中循环发送。如何遍历项目并延迟以便以正确的速率发送它们应该完全独立于代码的实际结构。

与其提前担心会影响您的发送速率的延迟,您要做的是自适应延迟。因此,您计算出发送实际花费了多长时间,然后在进行另一次发送之前延迟您想要等待的剩余时间。如果您的主要目标是您的平均发送速率而不是两次发送之间的实际延迟(我认为是这种情况),那么您只想看看到目前为止您发送元素所花费的时间与多少你发送的东西。由此,您可以自适应地延迟以几乎精确地将整体发送时间调整为您想要的。在数百或数千次发送中,您可以保证发送率几乎完全符合用户的要求。这是一个如何做到这一点的示例,将任何数据发送抽象为一个 print() 语句和一个随机延迟:

import time
import random

# Send this many items per second
sends_per_second = 10

# Simulate send time by introducing a random delay of at most this many seconds
max_item_delay_seconds = .06

# How many items to send
item_count = 100

# Do something representing a send, introducing a random delay
def do_one_item(i):
time.sleep(random.random() * max_item_delay_seconds)
print("Sent item {}".format(i))

# Record the starting time
start_time = time.time()

# For each item to send...
for i in range(item_count):

# Send the item
do_one_item(i)

# Compute how much time we've spent so far
time_spent = time.time() - start_time

# Compute how much time we want to have spent so far based on the desired send rate
should_time = (i + 1) / sends_per_second

# If we're going too fast, wait just long enough to get us back on track
if should_time > time_spent:
print("Delaying {} seconds".format(should_time - time_spent))
time.sleep(should_time - time_spent)

time_spent = time.time() - start_time
print("Sent {} items in {} seconds ({} items per second)".format(item_count, time_spent, item_count / time_spent))

缩略输出:

Sent item 0
Delaying 0.06184182167053223 seconds
Sent item 1
Delaying 0.0555738925933838 seconds
...
Sent item 98
Delaying 0.036808872222900746 seconds
Sent item 99
Delaying 0.03746294975280762 seconds
Sent 100 items in 10.000335931777954 seconds (9.999664079506683 items per second)

如您所见,尽管代码为每次发送引入了随机延迟,因此延迟逻辑必须计算所有地方的延迟,但实际实现的发送速率恰好达到 5 左右的要求小数位。

您可以玩这个例子中的数字。您应该能够说服自己,除非每次发送都需要很长时间才能跟上您请求的速率,否则您可以使用这种逻辑拨入您想要的任何发送速率。您还可以看到,您添加了过多的模拟延迟来表示发送时间,这样您就无法跟上所需的速率,您将不会收到任何延迟调用,代码只会尽可能快地发送项目。

关于python - 是否可以以特定速度发送数据(每秒 x 项),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56640231/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com