为 Shutil 添加多线程?!
对于一个文章开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《为 Shutil 添加多线程?!》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

讨论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
今天关于《为 Shutil 添加多线程?!》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
Leetcode:交替合并字符串
- 上一篇
- Leetcode:交替合并字符串
- 下一篇
- 优化 Web 性能:最佳实践和技术
-
- 文章 · python教程 | 1天前 | 线程池 · Python 线程池 concurrent.futures 任务取消 Future.cancel
- Python concurrent.futures.Future.cancel 怎样判断任务能否取消
- 143浏览 收藏
-
- 文章 · python教程 | 1天前 | 标准库 · HTTP服务 · 多线程 · Python教程 · Python 并发请求 http.server ThreadingHTTPServer ThreadingMixIn BaseHTTPRequestHandler
- Python http.server ThreadingHTTPServer 怎样处理并发请求
- 481浏览 收藏
-
- 文章 · python教程 | 1天前 |
- Python tarfile.TarInfo.replace 怎样复制归档成员属性
- 308浏览 收藏
-
- 文章 · python教程 | 1天前 | 并发编程 · Python教程 · Python 多进程 multiprocessing forkserver 启动上下文
- Python multiprocessing forkserver 怎样处理进程启动上下文
- 232浏览 收藏
-
- 文章 · python教程 | 1天前 | 标准库 · 异步编程 · Python教程 · Python asyncio StreamReader readexactly IncompleteReadError 异步流
- Python asyncio.StreamReader.readexactly 怎样处理不足长度的输入
- 427浏览 收藏
-
- 文章 · python教程 | 1天前 |
- Python operator.length_hint 怎样为未知长度迭代器设置估计值
- 336浏览 收藏
-
- 文章 · python教程 | 1天前 | 标准库 · Python教程 · Python warnings catch_warnings simplefilter filterwarnings 警告过滤
- Python warnings context manager 怎样临时调整警告过滤
- 255浏览 收藏
-
- 文章 · python教程 | 1天前 | 调试 · python · 异步编程 · Python asyncio introspection current_task all_tasks
- Python asyncio introspection 怎样定位当前任务
- 120浏览 收藏
-
- 文章 · python教程 | 1天前 | 标准库 · Python教程 · Python 类型注解 Python 3.14 annotationlib get_annotations ForwardRef 延迟注解
- Python 3.14 annotationlib.get_annotations 怎样读取延迟注解
- 423浏览 收藏
-
- 文章 · python教程 | 1天前 |
- Python 3.14 跨解释器 Queue.put 的阻塞与 QueueFull 处理方案
- 157浏览 收藏
-
- 文章 · python教程 | 1天前 | xml · python · Python xml xml.etree.ElementTree canonicalize C14N
- Python xml.etree.ElementTree.canonicalize 怎样生成稳定的 XML 文本
- 151浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 1156次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 1141次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 1320次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 1261次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 1118次使用
-
- Python TaskGroup 怎样让子任务失败统一收敛
- 2026-11-12 501浏览
-
- Python xml.dom.minidom.unlink 怎样释放不再使用的 DOM 树引用
- 2026-10-27 501浏览
-
- Python typing 怎样用 TypeIs 缩小类型
- 2026-10-24 501浏览
-
- Python sqlite3 Connection serialize 怎么导出数据库快照:备份窗口、内存占用与恢复校验
- 2026-08-26 501浏览
-
- Python监控网页状态:requests异常处理实战
- 2026-05-29 501浏览

