我正在尝试使用多线程和/或多处理来加速我的脚本。本质上,我有一个从 CSV 读取的 10,000 个子网列表,我想将其转换为 IPv4 对象,然后存储在数组中。
我的基本代码如下,执行时间大约为 300 毫秒:
aclsConverted = []
def convertToIP(ip):
aclsConverted.append(ipaddress.ip_network(ip))
for y in acls:
convertToIP(y['srcSubnet'])
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用并发.futures 线程,它可以工作,但速度慢 3-4 倍,如下所示:
aclsConverted = []
def convertToIP(ip):
aclsConverted.append(ipaddress.ip_network(ip))
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
for y in acls:
executor.submit(convertToIP,y['srcSubnet'])
Run Code Online (Sandbox Code Playgroud)
然后,如果我尝试使用并发。futures 处理速度会慢 10-15 倍,并且数组为空。代码如下
aclsConverted = []
def convertToIP(ip):
aclsConverted.append(ipaddress.ip_network(ip))
with concurrent.futures.ProcessPoolExecutor(max_workers=20) as executor:
for y in acls:
executor.submit(convertToIP,y['srcSubnet'])
Run Code Online (Sandbox Code Playgroud)
我运行它的服务器有 28 个物理核心。
任何关于我可能做错的事情的建议将不胜感激!