返回列表 发帖

[技术讨论] python3 多线程浏览文件夹

# 反而比单线程慢。
# 是cpu限制了吗?双核cpu
# 线程暴增!
# 方法或者方向错了?
'''
# 多线程加递归
# BUG未知
# 测试版
# 可以导入re模块正则匹配文件
# by GIN
# 2020/07/28
'''
#coding=utf-8
import os
import threading
import time
COUNT = 0 #文件数量
P = r'd:\\'
def test(fun):
    def pk(*args, **kw):
        b = time.time()
        fun(*args, **kw)
        print(time.time() - b)
    return pk
def dir_parse(path):
    # global COUNT
    # print(path)
    for root,dirs,files in os.walk(path):
        #print(path, '===',len(files)) #当前文件夹下面的文件数量
        global COUNT
        COUNT += len(files)
        if dirs:
            th = [mythread(dir_parse, root + os.sep + i) for i in dirs]
            for i in th:
                i.start()
            for j in th:
                j.join()
            dirs.clear()
            # return [os.path.join(root,i) for i in dirs]
        else:
            return None
class mythread(threading.Thread):
    def __init__(self, fun, agrs):
        threading.Thread.__init__(self)
        self.fun = fun
        self.agrs = agrs
    def run(self):
        self.fun(self.agrs)
def nothread(path):
    for root,dirs,files in os.walk(path):
        global COUNT
        # print(dirs)
        COUNT += len(files)
@test        
def main():
    dir_parse(P)
    print(COUNT)
@test
def main1():
    global COUNT
    COUNT = 0
    nothread(P)
    print(COUNT)
if __name__ == '__main__':
    main()
    main1()COPY
result:
20926
0.5148007869720459
20926
0.42220091819763184
请按任意键继续. . .COPY

返回列表