Python中的threads并行计算

工作中,遇到了API抓取与QPS并发量计算的问题。

自己测试了一下:在普通网速下,Python单核运算的QPS只能在13上下。但API接口对应的上界限为200,浪费了好多。

使用Threads并行运算

查看一下电脑CPU的内核数量,设备管理器-处理器中显示有12核,可以并行计算的。
我的电脑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了。缩短了时间,又避免浪费。


您的一个赞,就是对我的支持的动力,感谢!💪

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值