我尝试比较2个csv文件,每个文件包含100000行和10列。我运行这个代码它工作,但它只使用一个CPU的线程,而我有8个核心。我希望这段代码使用所有的cpu线程。我有搜索,我发现了并行的想法。但是当我尝试在这个python代码中对for循环应用并行时,它不起作用。如何申请并行此代码?提前谢谢你的帮助!
import csv
#read csv files
f1= file('host.csv','r')
f2= file('master.csv','r')
f3= file('results.csv','w')
c1=csv.reader(f1)
c2=csv.reader(f2)
next(c2, None)
c3=csv.writer(f3)
#for loop compare row in host csv file
master_list = list(c2)
for row in c1:
row=1
found = False
colA = str(row[0]) #protocol
colB = str(row[11])
colC = str(row[12])
colD = str(row[13])
colE = str(row[14])
#loop in each row of master csv file
for master_row in master_list:
results_row=row
colBf2 = str(master_row[4])
colCf2 = str(master_row[5])
colDf2 = str(master_row[6])
colEf2 = str(master_row[7])
colFf2 = str(master_row[3])
#check condition
if colA == 'icmp':
#sub condiontion
if colB == colBf2 and colD == colDf2:
results_row.append(colFf2)
found = True
break
row = row + 1
else:
if colB == colBf2 and colD == colDf2 and colE == colEf2:
results_row.append(colFf2)
found = True
break
row =row+1
if not found:
results_row.append('Not Match')
c3.writerow(results_row)
f1.close()
f2.close()
f3.close()
答案 0 :(得分:0)
昂贵的任务是内部循环,它为每个主机行重新扫描主表。由于python执行协作多线程(您可以搜索“python GIL”),因此一次只运行一个线程,因此多个线程不会加速cpu绑定操作。您可以生成子进程,但是您必须权衡将数据与工作进程相比的成本和速度增益。
或者,优化您的代码。而不是并行运行,而是索引主服务器。您可以交换昂贵的100000条记录扫描,以便快速查找字典。
我冒昧地将with
子句添加到您的代码中以保存几行,并且还跳过了colA
等等...(使用命名索引)来保持代码较小。
import csv
# columns of interest
A, B, C, D, E, F = 0, 11, 12, 13, 14, 3
# read and index column F in master by (B,D) and (B,D,E), discarding
# duplicates for those keys
col_index = {}
with open('master.csv') as master:
next(master)
for row in csv.reader(master):
key = row[B], row[D]
if key not in col_index:
col_index[key] = row[F]
key = row[B], row[D], row[E]
if key not in col_index:
col_index[key] = row[F]
#read csv files
with open('host.csv') as f1, open('results.csv','w') as f3:
c1=csv.reader(f1)
c3=csv.writer(f3)
for row in c1:
if row[A] == "icmp":
indexer = (row[B], row[D])
else:
indexer = (row[B], row[D], row[E])
row.append(col_index.get(indexer, 'Not Match'))
c3.writerow(row)