为什么当我使用 curl 回调进度时文件下载速度很慢?

Why is the file downloading work slowly when I use my callback progress with curl?

我有这个简单的 python 脚本,它使用 curl 下载文件。它还计算带宽。这是整个脚本:

import pycurl
import time

next_time = 0

# Callback function invoked when download/upload has progress
def progress(download_t, download_d, upload_t, upload_d):
    global next_time
    if time.time() >= next_time:
        print("Total to download", download_t)
        print("Total downloaded", download_d)
        print("Total to upload", upload_t)
        print("Total uploaded", upload_d)
        download_speed = (download_d / 1000000 * 8) / 10
        print(" download_speed", download_speed)
        next_time = time.time() + 10


c = pycurl.Curl()
c.setopt(c.URL, "https://mysample_domain.com/speed-test/test/1G.dat")
c.setopt(c.NOPROGRESS, False)
c.setopt(c.XFERINFOFUNCTION, progress)
start_time = time.time()
next_time = time.time() + 10
c.perform()
print('after download, duration = ', time.time() - start_time)

问题是,当我使用回调进度时,文件下载需要 459 秒。当我删除这两行时,文件在 210 秒内下载完毕。为什么我在方法进度中的计算会冻结下载速度?

c.setopt(c.NOPROGRESS, False)
c.setopt(c.XFERINFOFUNCTION, progress)

我分析了您的代码,得出的结论是进度函数不会造成任何显着的减速。事实上,您的代码在进度函数中只花费了总 运行 时间的 0.2%(在 20 秒的下载期间有大约 40k 次调用)。

我也运行下载了很多次,发现有时候下载没有进度,有时候有进度的下载时间明显比平时长很多(大约是平时的2-3倍)。可能是网络问题issues/bottlenecks,也可能是pycurl的问题,但绝对不是你的进度函数造成的。