讨论shutil.copytree添加多线程
** 我在 python 上写的讨论:https://discuss.python.org/t/add-multithreading-to-shutil-copytree/62078 **
背景
shutil 是 python 中一个非常有用的模块。你可以在github中找到它:https://github.com/python/cpython/blob/master/lib/shutil.py
shuutil.copytree 是一个将文件夹复制到另一个文件夹的函数。
在这个函数中,调用_copytree函数进行复制。
_copytree 有什么作用?
- 忽略指定的文件/目录。
- 创建目标目录。
- 在处理符号链接时复制文件或目录。
- 收集并最终提出遇到的错误(例如权限问题)。
- 将源目录的元数据复制到目标目录。
问题
_当文件数量较多或文件大小较大时,copytree速度不是很快
在这里测试:
import os
import shutil
os.mkdir('test')
os.mkdir('test/source')
def bench_mark(func, *args):
import time
start = time.time()
func(*args)
end = time.time()
print(f'{func.__name__} takes {end - start} seconds')
return end - start
# write in 3000 files
def write_in_5000_files():
for i in range(5000):
with open(f'test/source/{i}.txt', 'w') as f:
f.write('hello world' + os.urandom(24).hex())
f.close()
bench_mark(write_in_5000_files)
def copy():
shutil.copytree('test/source', 'test/destination')
bench_mark(copy)
结果是:
write_in_5000_files 需要 4.084963083267212 秒
复制需要 27.12768316268921 秒
我做了什么
我使用多线程来加速复制过程。我将函数重命名为_copytree_single_threaded,添加一个新函数_copytree_multithreaded。这是copytree_multithreaded:
def _copytree_multithreaded(src, dst, symlinks=false, ignore=none, copy_function=shutil.copy2,
ignore_dangling_symlinks=false, dirs_exist_ok=false, max_workers=4):
"""recursively copy a directory tree using multiple threads."""
sys.audit("shutil.copytree", src, dst)
# get the entries to copy
entries = list(os.scandir(src))
# make the pool
with threadpoolexecutor(max_workers=max_workers) as executor:
# submit the tasks
futures = [
executor.submit(_copytree_single_threaded, entries=[entry], src=src, dst=dst,
symlinks=symlinks, ignore=ignore, copy_function=copy_function,
ignore_dangling_symlinks=ignore_dangling_symlinks,
dirs_exist_ok=dirs_exist_ok)
for entry in entries
]
# wait for the tasks
for future in as_completed(futures):
try:
future.result()
except exception as e:
print(f"failed to copy: {e}")
raise
我添加了一个判断来选择是否使用多线程。
if len(entries) >= 100 or sum(os.path.getsize(entry.path) for entry in entries) >= 100*1024*1024:
# multithreaded version
return _copytree_multithreaded(src, dst, symlinks=symlinks, ignore=ignore,
copy_function=copy_function,
ignore_dangling_symlinks=ignore_dangling_symlinks,
dirs_exist_ok=dirs_exist_ok)
else:
# single threaded version
return _copytree_single_threaded(entries=entries, src=src, dst=dst,
symlinks=symlinks, ignore=ignore,
copy_function=copy_function,
ignore_dangling_symlinks=ignore_dangling_symlinks,
dirs_exist_ok=dirs_exist_ok)
测试
我在源文件夹中写入了 50000 个文件。基准标记:
def bench_mark(func, *args):
import time
start = time.perf_counter()
func(*args)
end = time.perf_counter()
print(f"{func.__name__} costs {end - start}s")
写在:
import os
os.mkdir("test")
os.mkdir("test/source")
# write in 50000 files
def write_in_file():
for i in range(50000):
with open(f"test/source/{i}.txt", 'w') as f:
f.write(f"{i}")
f.close()
两个比较:
def copy1():
import shutil
shutil.copytree('test/source', 'test/destination1')
def copy2():
import my_shutil
my_shutil.copytree('test/source', 'test/destination2')
- “my_shutil”是我修改过的shutil版本。
copy1 花费 173.04780609999943s
copy2 花费 155.81321870000102s
copy2 比 copy1 快很多。你可以跑很多次。
优点和缺点
使用多线程可以加快复制过程。但会增加内存占用。但我们不需要在代码中重写多线程。
结尾
这是我第一次在 python.org 上写讨论。如果有任何问题,请告诉我。谢谢你。
我的github:https://github.com/mengqinyuan
我的开发者:https://dev.to/mengqinyuan