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)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值