如何统计最后一秒下载了多少数据? (FTP)

How to count how many data has been downloaded in the last second? (FTP)

我想知道最近1秒下载了多少数据
我还没有代码但我想知道我应该什么时候开始计算这 1 秒以及如何计算。
我应该在 retrbinary() 之前还是之后开始计数?还是我完全错了?

首先,传输进度显示有现成的实现,包括传输速度。

举个例子,progressbar2模块。参见 Show FTP download progress in Python (ProgressBar)

进度条2默认显示FileTransferSpeed widget,自下载开始以来的平均传输速度是多少。

不过请注意,速度显示器通常不会显示这样的速度。他们显示过去几秒钟的平均速度。这使得该值更具信息性。 progressbar2 有 AdaptiveTransferSpeed widget for that. But it seems to be broken.


如果您想自己实现计算,并且对自下载开始以来的简单平均传输速度感到满意,那很简单:

from ftplib import FTP
import time
import sys
import datetime

ftp = FTP(host, user, passwd)

print("Downloading")
total_length = 0
start_time = datetime.datetime.now()

def write(data):
   f.write(data)
   global total_length
   global start_time
   total_length += sys.getsizeof(data)
   elapsed = (datetime.datetime.now() - start_time)
   speed = (total_length / elapsed.total_seconds())
   print("\rElapsed: {0} Speed: {1:.2f} kB/s".format(str(elapsed), speed / 1024), end="")

f = open('file.dat', 'wb')
ftp.retrbinary("RETR /file.dat", write)
f.close()

print()
print("done")    

最后几秒的平均速度是比较难计算的方法。您必须记住过去时刻传输的数据量。从 AdaptiveTransferSpeed 窃取(并修复)代码,你会得到类似的东西:

sample_times = []
sample_values = []
INTERVAL = datetime.timedelta(milliseconds=100)
last_update_time = None
samples=datetime.timedelta(seconds=2)
total_length = 0

def write(data):
   f.write(data)

   global total_length

   total_length += sys.getsizeof(data)
   elapsed = (datetime.datetime.now() - start_time)

   if sample_times:
       sample_time = sample_times[-1]
   else:
       sample_time = datetime.datetime.min

   t = datetime.datetime.now()
   if t - sample_time > INTERVAL:
       # Add a sample but limit the size to `num_samples`
       sample_times.append(t)
       sample_values.append(total_length)

       minimum_time = t - samples
       minimum_value = sample_values[-1]
       while (sample_times[2:] and
              minimum_time > sample_times[1] and
              minimum_value > sample_values[1]):
           sample_times.pop(0)
           sample_values.pop(0)

   delta_time = sample_times[-1] - sample_times[0]
   delta_value = sample_values[-1] - sample_values[0]
   if delta_time:
       speed = (delta_value / delta_time.total_seconds())

       print("\rElapsed: {0} Speed: {1:.2f} kB/s".format(
           str(elapsed), speed / 1024), end="")

ftp.retrbinary("RETR /medium.dat", write)