初学多线程:
直接贴处下对比
(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秒