【问题标题】:Is there any way to replace for loop to Multiple-threading for speedy time execution?有没有办法将 for 循环替换为多线程以快速执行?
【发布时间】:2020-12-01 20:49:54
【问题描述】:

为了详细了解,我附上了文件链接。

Indetail understanding code

我在列表中有数据,其语法类似:

i = [a.b>c.d , e.f.g>h.i.j ]
l = [a.b , e.f.g ]
n = [a.b>c.d , e.f.g ]

例如列表的每个元素都有多个用“.”分隔的子元素。和">"

for i in range(0, len(l)):
reac={}
reag={}
t = l[i].split(">")
REAC = t[0]
Reac = REAC.split(".")

for o in range(len(Reac)):

    reaco = "https://ai.chemistryinthecloud.com/smilies/" + Reac[o]

    respo = requests.get(reaco)
    reac[o] ={"Smile":Reac[o],"Details" :respo.json()}

if (len(t) != 1):
    REAG = t[1]
    Reag = REAG.split(".")
    for k in range(len(Reag)):

        reagk = "https://ai.chemistryinthecloud.com/smilies/" + Reag[k]
        repo = requests.get(reagk)
        reag[k] = {"Smile": Reag[k], "Details" :repo.json()}
    res = {"Reactants": list(reac.values()), "Reagents": list(reag.values())}
    boo.append(res)
else:
    res = {"Reactants": list(reac.values()), "Reagents": "No reagents"}
    boo.append(res)

我们已经分离了所有元素,并且对于每个元素,我们都调用了 3rd 方 API。这太浪费时间了。

有什么办法可以减少这个时间并针对循环进行优化?

回复大约需要 1 分钟。我们希望优化到 5-10 秒。

【问题讨论】:

  • 如果外部 API 需要 1 分钟,那么您可以减少 io 时间的最接近的时间是 1 分钟。你不能把它减少到 5-10 秒。

标签: python-3.x for-loop python-multithreading


【解决方案1】:

您可以启动多个请求并在完成后处理它们 ThreadPoolExecutor。 这可能会加快一点。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多