我正在写一个脚本从一个网站下载视频。我添加了一个报告钩子来获取下载进度。到目前为止,它显示了下载数据的百分比和大小。我觉得增加下载速度和预计到达时间会很有趣。
问题是,如果我用一个简单的speed = chunk_size/time
显示的速度足够精确,但是像疯了一样跳来跳去。所以,我使用了下载单个块的时间历史。比如,speed = chunk_size*n/sum(n_time_history)
。
现在它显示了一个稳定的下载速度,但它肯定是错误的,因为它的值以几位/秒为单位,而下载的文件显然以更快的速度增长。
有人能告诉我我哪里出错了吗?在
这是我的密码。在
def dlProgress(count, blockSize, totalSize):
global init_count
global time_history
try:
time_history.append(time.monotonic())
except NameError:
time_history = [time.monotonic()]
try:
init_count
except NameError:
init_count = count
percent = count*blockSize*100/totalSize
dl, dlu = unitsize(count*blockSize) #returns size in kB, MB, GB, etc.
tdl, tdlu = unitsize(totalSize)
count -= init_count #because continuation of partial downloads is supported
if count > 0:
n = 5 #length of time history to consider
_count = n if count > n else count
time_history = time_history[-_count:]
time_diff = [i-j for i,j in zip(time_history[1:],time_history[:-1])]
speed = blockSize*_count / sum(time_diff)
else: speed = 0
n = int(percent//4)
try:
eta = format_time((totalSize-blockSize*(count+1))//speed)
except:
eta = '>1 day'
speed, speedu = unitsize(speed, True) #returns speed in B/s, kB/s, MB/s, etc.
sys.stdout.write("\r" + percent + "% |" + "#"*n + " "*(25-n) + "| " + dl + dlu + "/" + tdl + tdlu + speed + speedu + eta)
sys.stdout.flush()
Edit:
Corrected the logic. Download speed shown is now much better.
As I increase the length of history used to calculate the speed, the stability increases but sudden changes in speed (if download stops, etc.) aren't shown.
How do I make it stable, yet sensitive to large changes?
我意识到现在的问题更倾向于数学,但如果有人能帮我解决问题或给我指出正确的方向,那就太好了。
另外,请告诉我是否有更有效的方法来实现这一点。在
为了使其更稳定,并且在下载峰值上升或下降时不会发生反应,您还可以添加以下内容:
^{pr2}$这将删除
time_history
中的最高和最低峰值,这将使显示的数字更加稳定。如果你想挑肥拣瘦,你可以在移除之前生成权重,然后使用time_diff.index(min(time_diff))
过滤映射值。在同样,使用非线性函数(如
sqrt()
)来生成权重将给您带来更好的结果。哦,正如我在评论中所说的:添加统计方法来过滤时间应该稍微好一点,但是我怀疑它不值得增加额外的开销。在相关问题 更多 >
编程相关推荐