我正在尝试加快我用python处理文件的时间。我的想法是将任务分成n个线程。
例如,如果我有一个包含1300个项目的文件。我希望每个线程处理第n个项目。每个项目都不依赖于其他任何项目,因此这里的顺序无关紧要
因此每个线程的工作流程将是这样的:
1) open file
2) iterate through items
3) if nth item then process, otherwise continue
我正在使用线程库来执行此操作,但是我看不到任何性能改进。
这是伪代码:
def driver(self):
threads = []
# Just picked 10 as test so trying to create 10 threads
for i in range(0,10):
threads.append(threading.Thread(target=self.workerFunc, args=(filepath, i, 10)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
def workerFunc(self, filepath):
with open(filepath, 'rb') as file:
obj = ELFFile(file)
for item in obj.items:
if (item is not nth item):
continue
else:
process this item
由于每个线程都在读取文件,因此它应该能够自由扫描文件,而不必关心其他线程在做什么或被它们阻塞,对吗?
我在这里俯瞰什么?
我唯一能想到的是,我用来格式化这些文件的库(pyelftool ELFFile)内部有些东西正在阻塞,但我找不到。还是我的计划存在根本缺陷?
编辑:只是要注意,我在其上运行该系统的系统上有32 cpus