python - 如何统计上一秒下载了多少数据? (FTP)

标签 python python-3.x download ftp ftplib

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

最佳答案

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

例如,progressbar2 模块。请参阅Show FTP download progress in Python (ProgressBar) .

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

但请注意,速度显示通常不会显示这样的速度。它们显示过去几秒钟的平均速度。这使得该值更具信息性。进度条2有AdaptiveTransferSpeed widget为了那个原因。但它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)

关于python - 如何统计上一秒下载了多少数据? (FTP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57924241/

相关文章:

python - 检查日期是否为没有 pytz 的时区的夏令时

python - 将网格导入 Fipy 后如何从 python 访问 gmsh 代码?

python - 为什么有些 Python 异常是小写的?

python - 使用 Selenium 和 Firefox 版本 40,如何下载文件?

android - 如何在 Fragment 中显示 ProgressDialog 以供下载

python - 去掉边缘的黑线

python - Plotly:如何自定义图例?

python - Pywinauto app = Application.start() 不起作用并给出错误

python - 解析 HTML 以检索术语

java - 使用 OkHttp 下载损坏的文件