【发布时间】:2021-08-08 04:29:50
【问题描述】:
所以目前我有这个代码,它可以完美地按照我的预期工作。
import urllib.request
from tqdm import tqdm
with open("output.txt", "r") as file:
itemIDS = [line.strip() for line in file]
x = 0
for length in tqdm(itemIDS):
urllib.request.urlretrieve(
"https://imagemocksite.com?id="+str(itemIDS[x]),
"images/"+str(itemIDS[x])+".jpg")
x += 1
print("All images downloaded")
我四处寻找,发现的解决方案并不是我真正想要的。我有 200mbp/s,所以这不是我的问题。
我的问题是我的循环每秒迭代 1.1 - 1.57 次。我想加快速度,因为我有超过 5k 的图像要下载。它们每个也大约 1-5kb。
另外,如果有人有任何一般的代码提示,我将不胜感激!我正在学习python,它很有趣,所以我想尽可能地变得更好!
编辑: 使用下面关于 asyncio 的信息,我现在得到 1.7-2.1 It/s,哪个更好!可以更快吗?是不是我用错了?
import urllib.request
from tqdm import tqdm
import asyncio
with open("output.txt", "r") as file:
itemIDS = [line.strip() for line in file]
async def download():
x = 0
for length in tqdm(itemIDS):
await asyncio.sleep(1)
urllib.request.urlretrieve(
"https://imagemocksite.com?id="+str(itemIDS[x]),
"images/"+str(itemIDS[x])+".jpg")
x += 1
asyncio.run(download())
print("All images downloaded")
【问题讨论】:
-
如果服务器是瓶颈并且正在限制您的速率怎么办。那么你不能使循环更有效率。您或许可以通过多处理更快地下载图像。
-
您不会为此使用
multiprocessing,而是使用threading@Goion,因为这是一个 I/O 绑定任务,而不是 CPU 绑定 -
正如@Goion 所说,它可能确实受到服务器的限制。补充他的后一条评论;通常asyncio 库(或具有类似功能的库,如 Tornado)用于这些类型的 I/O 应用程序,因为多处理更适合于繁重的计算。相比之下,
asyncio在单个进程和单个线程上运行,但可以“暂停”一个函数(等待它)并继续执行程序的其余部分,同时等待基于 Python 协程的输入。 -
mp、线程和异步都是不错的选择。除了个人选择之外,我认为没有任何理由选择其中一个。
-
由于 GIL 的限制,我建议使用 mp。但是现在我认为多线程甚至异步都可以工作,因为大多数时候你无论如何都会等待。 Mp 可能只是浪费资源。
标签: python performance loops download