我试图用Python编写一个多线程程序来加速(低于1000).csv文件的复制.多线程代码比顺序方法运行得更慢.我用时间计算代码profile.py.我相信我一定做错了什么,但我不确定是什么.
环境:
该方法:
我将所有文件路径放在一个队列中,并创建4-8个工作线程从队列中拉出文件路径并复制指定的文件.在任何情况下,多线程代码都不会更快:
我假设这是一个I/O绑定任务,因此多线程应该有助于操作速度.
代码:
import Queue
import threading
import cStringIO
import os
import shutil
import timeit # time the code exec with gc disable
import glob # file wildcards list, glob.glob('*.py')
import profile #
fileQueue = Queue.Queue() # global
srcPath = 'C:\\temp'
destPath = 'D:\\temp'
tcnt = 0
ttotal = 0
def CopyWorker():
while True:
fileName = fileQueue.get()
fileQueue.task_done()
shutil.copy(fileName, destPath)
#tcnt += 1
print 'copied: ', tcnt, ' of …Run Code Online (Sandbox Code Playgroud)