微慑信息网

python 多线程遍历目录测试 の 一

初学多线程:


 

直接贴处下对比

(1)常规情况:

import threading
import os
import  time

def check_files(path):
    pathlist = os.listdir(path)
    for mpath in pathlist:
        mpath = path+'/'+mpath
        if os.path.isdir(mpath):
            check_files(mpath)
        else:
            reslist.append(mpath)

def main():
    global reslist
    reslist = []
    path='D:\Program Files'
    start =time.time()
    check_files(path)
    end =time.time()
    print ('cost time :',end-start)
    print ('files num is :',len(reslist))


if __name__ == '__main__':
    main()

(2)多线程:

import threading
import os
import  time

def check_files(path):
    pathlist = os.listdir(path)
    for mpath in pathlist:
        mpath = path+'/'+mpath
        if os.path.isdir(mpath):
            check_files(mpath)
        else:
            reslist.append(mpath)

def main():
    global reslist
    reslist = []
    path='D:\Program Files'
    start =time.time()
    threats =[]
    t = threading.Thread(target=check_files,args=(path,))
    threats.append(t)
    for thread in threats:
        thread.start()
    for thread in threats:
        thread.join()
    end = time.time()
    print ('cost time :',end-start)
    print ('files num is :',len(reslist))


if __name__ == '__main__':
    main()

执行结果没什么区别,因为该处仅仅是列出了文件名,但是如果有对文件的操作,区别有就有了:

如:增加了对图片文件是否包含二维码的判断:

在不使用多线程的情况下,总是1615个文件,204个目录的环境下,执行时间9.29秒

在使用多线程的情况下,总是1615个文件,204个目录的环境下,执行时间4.15秒

本文标题:python 多线程遍历目录测试 の 一
本文链接:
(转载请附上本文链接)
https://vulsee.com/archives/vulsee_2021/0906_14655.html
转载请附本站链接,未经允许不得转载,,谢谢:微慑信息网-VulSee.com » python 多线程遍历目录测试 の 一
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

微慑信息网 专注工匠精神

访问我们联系我们