python concurrent.futures模块与线程模块threading比较-复制文件

任务:复制指定文件夹的文件
1.使用python的并发库concurrent.futures
2.使用线程threading
3.普通方式
性能比较:
concurrent.futures进程异步 39秒
多线程无阻塞 0.17秒,线程阻塞 58秒
普通方式单线程 53秒
结论:使用多线程无阻塞遥遥领先其它方法.

# -*- coding: utf-8 -*- 
import time
import threading
from concurrent.futures import ThreadPoolExecutor
from threading import Thread
from queue import Queue
from shutil import copy
from os import listdir
from os.path import isfile,join

def concurrent_test():  #异步进程
   with ThreadPoolExecutor(max_workers=100) as e:
        for f in (fn for fn in listdir("testfile")):
              src=join("testfile",f)
              if isfile(src):
                 dst=join("backup1",f)
                 e.submit(copy,src,dst)
  



class mythread(threading.Thread):  #多线程
    def __init__(self,f):
        #threading.Thread.__init__(self)
        super().__init__()
        self.f=f        
    def run(self):    #重写run()方法,实现建立文件写入内容的功能
              src=join("testfile",self.f)
              if isfile(src):
                 dst=join("backup2",self.f)
                 copy(src,dst)



def copy_paste():  #普通复制粘贴
      for f in (fn for fn in listdir("testfile")):
              src=join("testfile",f)
              if isfile(src):
                 dst=join("backup3",f)
                 copy(src,dst)




                 
if __name__=="__main__":

   
    start=time.time()
    concurrent_test()
    end=time.time()
    print("进程异步",end-start)



    start=time.time()
    t1=[]
    for f in (fn for fn in listdir("testfile")):  
        t=mythread(f)
        t1.append(t)
    for i in t1:
        i.start()                  #线程加join(),time 34.40635061264038,不阻塞
        #i.join()
    end=time.time()
    print("多线程无阻塞",end-start)



    start=time.time()
    copy_paste()
    end=time.time()
    print("单线程",end-start)

你可能感兴趣的:(Python,python,thread,多进程)