工作中,遇到了API抓取与QPS并发量计算的问题。
自己测试了一下:在普通网速下,Python单核运算的QPS只能在13上下。但API接口对应的上界限为200,浪费了好多。
使用Threads并行运算
查看一下电脑CPU的内核数量,设备管理器-处理器中显示有12核,可以并行计算的。
在Python中对应的代码也很简单,依托 threads 库并行计算。
import threading
# 先定义两个要计算的函数
def fun1():
...
def fun2():
...
# 添加到并行集合中
threads=[]
threads.append(threading.Thread(target=fun1))
threads.append(threading.Thread(target=fun1))
#开跑
for t in threads:
t.start()
附加一段我API接口的对应程序。
out1=out2=out3=out4=[]
def part1():
for i in range(0,25000,1):
url1='https://apis.map.qq.com/ws/distance/v1/matrix/?mode=bicycling&from='+str(data.iloc[i,1])+','+str(data.iloc[i,0])+'&to='+str(data.iloc[i,3])+','+str(data.iloc[i,2])+'&key=Mykey'
try:
out1.extend([requests.get(url1).json()['result']['rows'][0]['elements'][0]['distance']])
except:
out1.extend([str(i)+'Bug'])
## 2-4同理,省略掉
threads=[]
threads.append(threading.Thread(target=part1))
threads.append(threading.Thread(target=part2))
threads.append(threading.Thread(target=part3))
threads.append(threading.Thread(target=part4))
for t in threads:
t.start()
最高可以并行10条链,直接QPS上升到了峰值160了。缩短了时间,又避免浪费。
您的一个赞,就是对我的支持的动力,感谢!💪