使用Python进行多线程并行查找计数文件



我有一个代码,可以使用python检查文件夹中文件的数量和文件夹的其他细节,因为我想让它更快一点,所以我包含了多线程概念,每当它遇到根文件夹中的任何目录/文件夹时,都会对文件进行计数,就像它会分配一个线程,每当它得到一个目录时,就会对一个目录中的文件数量进行计数一样。创建的程序运行良好。但要想它是按顺序工作而不是并行工作。

这是我的代码:

root =  roots = 'C:/Users/'
count_of_file = 0

noOfFiles = local_time_of_oldest = local_time_of_newest= 0
subdir=""
N = 0
def Count_files_in_subd():
for root, dirs, files in os.walk(roots):
taggedrootdir = pathlib.Path(root)
thread = threading.Thread(target=findfiles, args=(taggedrootdir,files,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()

def findfiles(taggedrootdir,files):
folderstat = {}
folderstat['FolderPath'] = root
folderstat['count'] = len(files)
print(folderstat)

start_time = time.time()
Count_files_in_subd()
print("--- %s seconds ---" % (time.time() - start_time))

以及我将如何为共享路径使用相同的脚本

是。Python有一个称为";全局解释器锁定";一次只允许一个线程执行Python代码。真正获胜的唯一方法是让线程等待I/O,或者在自己管理事务的C库中执行。

话虽如此,在Windows中枚举目录从来都不是一项快速的任务。我已经用C++编写了基本上相同的工具,这只是需要时间。线程在I/O绑定时没有帮助。

一个选项是使用来自多处理的Pool对象库

您修改的代码:

import os, time
from   multiprocessing import Pool
def findfiles(taggedrootdir,files):
folderstat = {}
folderstat['FolderPath'] = taggedrootdir
folderstat['count'] = len(files)
return folderstat
if __name__ == '__main__':
roots = r'C:/Users/'
start_time = time.time()
args = ((root, files) for root, dirs, files in os.walk(roots))
for result in Pool().starmap(findfiles, args):
print(result)
print('--- %s seconds ---' % (time.time() - start_time))

与您版本的21.8相比,在我的python安装文件夹树上运行此程序需要0.5秒。

最新更新