如何解决如何并行化或使用多核来加快while循环?
我有一个带有16核处理器的实例,并且有一个while循环,如下所示,
count = 200000
num = 0
pbar = tqdm(total=count)
lst = []
while num <= count:
random_folder = os.path.join(path,np.random.choice(os.listdir(path)))
file_path = os.path.join(path,np.random.choice(os.listdir(random_folder)))
if not os.path.isdir(file_path):
lst.append(file_path)
pbar.update(1)
num += 1
当我尝试在服务器上运行此代码时,估计时间真的很长
0%| | 138/200000 [02:14<51:25:11,1.08it/s]
我尝试使用numpy来获得随机选择,但是它仍然很慢。有什么办法可以利用我的多核CPU并加快while循环的速度吗?它只是从子文件夹中收集随机文件。非常感谢您的帮助。谢谢
更新:
path = "/home/user12/pdf_files"
def get_random_file(num_of_files):
count = 0
random_files = []
while count < num_of_files:
random_folder = os.path.join(path,random.choice(os.listdir(path)))
file_path = os.path.join(path,random.choice(os.listdir(random_folder)))
if not os.path.isdir(file_path):
resumes_list.append(file_path)
count += 1
return random_files
with Pool(16) as p:
random_files = p.map(get_random_file,(1000/16,))
解决方法
您可以使用多重处理并同时使用所有内核。
请参见https://docs.python.org/3.8/library/multiprocessing.html
类似这样的东西:
from multiprocessing import Pool
def get_random_file(num_of_files):
# your logic goes here
count = 0
random_files = []
while count < num_of_files:
count += 1
pass
#get random file and append to 'random_files'
return random_files
if __name__ == '__main__':
with Pool(16) as p:
num_of_files = [200000/16 for i in range(1,16)]
random_files = p.map(get_random_file,num_of_files)
# random_files is a list of lists - you need to merge them into one list
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。