Python多线程如何提升计算效率 Python多线程并行计算实战

雪夜
发布: 2025-11-14 15:58:02
原创
243人浏览过
Python多线程适用于IO密集型任务如网络请求、文件读写和数据库查询,因GIL限制不适用于CPU密集型任务;1. 多线程可提升IO等待期间的资源利用率;2. 实战中使用threading模块或concurrent.futures可显著缩短批量请求耗时;3. CPU密集型任务应改用multiprocessing模块以绕过GIL实现并行计算。

python多线程如何提升计算效率 python多线程并行计算实战

Python多线程在提升计算效率方面有其特定适用场景,但需注意语言本身的限制。由于全局解释器锁(GIL)的存在,Python中的多线程并不能真正实现CPU密集型任务的并行执行。然而,在IO密集型任务中,多线程能显著提高程序的响应速度和资源利用率。

多线程适合的场景

理解何时使用多线程是关键。以下类型的任务更适合用多线程处理:

  • 网络请求:如同时抓取多个网页内容,等待时间远大于计算时间
  • 文件读写操作:涉及磁盘IO时,线程可在等待期间切换执行其他任务
  • 数据库查询:多个独立查询可并发发起,减少总耗时

实战:使用threading模块进行并行请求

以批量获取网页标题为例,展示多线程如何缩短整体执行时间:

import threading
import requests
from bs4 import BeautifulSoup
import time
<p>def fetch_title(url, results, index):
try:
response = requests.get(url, timeout=5)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.find('title').get_text() if soup.find('title') else 'No Title'
results[index] = title
except Exception as e:
results[index] = f"Error: {e}"</p><p>urls = [
"<a href="https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c">https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c</a>",
"<a href="https://www.php.cn/link/ef246753a70fce661e16668898810624">https://www.php.cn/link/ef246753a70fce661e16668898810624</a>",
"<a href="https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c">https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c</a>"
]</p><h1>单线程执行</h1><p>start = time.time()
results_single = []
for i, url in enumerate(urls):
temp_results = [None]
fetch_title(url, temp_results, 0)
results_single.append(temp_results[0])
print(f"单线程耗时: {time.time() - start:.2f}秒")</p><h1>多线程执行</h1><p>start = time.time()
threads = []
results_multi = [None] * len(urls)
for i, url in enumerate(urls):
t = threading.Thread(target=fetch_title, args=(url, results_multi, i))
threads.append(t)
t.start()</p><p>for t in threads:
t.join()</p><p>print(f"多线程耗时: {time.time() - start:.2f}秒")
print("结果:", results_multi)</p>
登录后复制

使用concurrent.futures简化线程管理

对于更简洁的代码结构,推荐使用concurrent.futures.ThreadPoolExecutor

立即学习Python免费学习笔记(深入)”;

算家云
算家云

高效、便捷的人工智能算力服务平台

算家云 37
查看详情 算家云
from concurrent.futures import ThreadPoolExecutor
import requests
<p>def get_status(url):
try:
return requests.get(url, timeout=3).status_code
except:
return -1</p><p>with ThreadPoolExecutor(max_workers=5) as executor:
urls = ["<a href="https://www.php.cn/link/98a733901e53052474f2320d0a3a9473">https://www.php.cn/link/98a733901e53052474f2320d0a3a9473</a>"] * 10
statuses = list(executor.map(get_status, urls))
print("状态码:", statuses)</p>
登录后复制

这种方式自动管理线程生命周期,避免手动创建和join线程,代码更清晰且不易出错。

CPU密集型任务的替代方案

若任务主要为数值计算、图像处理等CPU密集型操作,应考虑使用multiprocessing模块绕过GIL限制:

from multiprocessing import Pool
import math
<p>def cpu_task(n):
return sum(i * i for i in range(n))</p><p>if <strong>name</strong> == '<strong>main</strong>':
data = [100000] * 8
with Pool(4) as p:
result = p.map(cpu_task, data)
print("计算完成")</p>
登录后复制

多进程能真正利用多核优势,适合纯计算场景。

基本上就这些。选择多线程还是多进程,取决于任务类型。IO等待多就用线程,计算重就用进程。合理使用工具,才能有效提升效率。

以上就是Python多线程如何提升计算效率 Python多线程并行计算实战的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号