Python单线程、多线程与多进程性能对比实测:GIL限制下的效率分析
本文通过实际代码实验,对比Python中单线程、多线程和多进程在CPU密集、IO密集及网络请求场景下的执行效率。结果显示,受GIL限制,多线程在CPU密集型任务中性能甚至低于单线程,但在网络阻塞场景下优势显著;多进程则能充分利用多核优势,在各类场景中均表现优异,尤其在CPU密集型任务中效率最高。
Python并发模型与GIL机制概述
在Python中,多进程的性能表现通常明显优于多线程,这主要归因于CPython解释器中全局解释器锁(GIL)对多线程并发执行造成的性能约束。
Python作为一种解释型语言,其运行机制中引入了全局锁(GIL)。这意味着在使用多线程(Thread)时,同一时刻只能有一个线程执行字节码,无法真正发挥多核CPU的计算优势。相比之下,使用多进程(Multiprocess)可以绕过GIL的限制,每个进程拥有独立的GIL,从而充分利用多核资源,显著提升执行效率。
实验设计与场景分类
为了验证上述理论,我们设计并执行了对比实验。
根据相关资料,若多线程处理的是CPU密集型任务,其效率提升有限,甚至可能因线程上下文频繁切换导致性能下降,此时推荐使用多进程;若处理的是IO密集型任务,多线程可以利用IO阻塞等待的时间并发执行其他任务,从而提升整体效率。基于此,我们针对不同场景进行了具体的效率对比测试。
测试环境配置
| 操作系统 | CPU | 内存 | 硬盘 |
|---|---|---|---|
| Windows 10 | 双核 | 8GB | 机械硬盘 |
测试代码实现
首先,引入实验所需的Python标准库及第三方模块。
import requests
import time
from threading import Thread
from multiprocessing import Process
接着,定义用于模拟CPU密集型计算的函数。
def count(x, y):
# 使程序完成150万计算
c = 0
while c < 500000:
c += 1
x += x
y += y
然后,定义用于模拟IO密集型文件读写操作的函数。
def write():
f = open("test.txt", "w")
for x in range(5000000):
f.write("testwrite\n")
f.close()
def read():
f = open("test.txt", "r")
lines = f.readlines()
f.close()
随后,定义用于模拟网络请求的函数。
_head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'}
url = "http://www.tieba.com"
def http_request():
try:
webPage = requests.get(url, headers=_head)
html = webPage.text
return {"context": html}
except Exception as e:
return {"error": e}
接下来,分别测试线性执行IO密集操作、CPU密集操作以及网络请求密集型操作所消耗的时间,作为基准对照。
# CPU密集操作
t = time.time()
for x in range(10):
count(1, 1)
print("Line cpu", time.time() - t)
# IO密集操作
t = time.time()
for x in range(10):
write()
read()
print("Line IO", time.time() - t)
# 网络请求密集型操作
t = time.time()
for x in range(10):
http_request()
print("Line Http Request", time.time() - t)
线性执行基准测试
以下是线性执行模式下的测试结果输出。
CPU密集:95.6059999466、91.57099986076355 92.52800011634827、 99.96799993515015 IO密集:24.25、21.76699995994568、21.769999980926514、22.060999870300293 网络请求密集型: 4.519999980926514、8.563999891281128、4.371000051498413、4.522000074386597、14.671000003814697
多线程并发性能测试
随后,测试多线程并发执行CPU密集操作所需的时间。
counts = []
t = time.time()
for x in range(10):
thread = Thread(target=count, args=(1,1))
counts.append(thread)
thread.start()
e = counts.__len__()
while True:
for th in counts:
if not th.is_alive():
e -= 1
if e <= 0:
break
print(time.time() - t)
Output: 99.9240000248 、101.26400017738342、102.32200002670288
接着,测试多线程并发执行IO密集操作所需的时间。
def io():
write()
read()
t = time.time()
ios = []
t = time.time()
for x in range(10):
thread = Thread(target=count, args=(1,1))
ios.append(thread)
thread.start()
e = ios.__len__()
while True:
for th in ios:
if not th.is_alive():
e -= 1
if e <= 0:
break
print(time.time() - t)
Output: 25.69700002670288、24.02400016784668
然后,测试多线程并发执行网络密集操作所需的时间。
t = time.time()
ios = []
t = time.time()
for x in range(10):
thread = Thread(target=http_request)
ios.append(thread)
thread.start()
e = ios.__len__()
while True:
for th in ios:
if not th.is_alive():
e -= 1
if e <= 0:
break
print("Thread Http Request", time.time() - t)
Output: 0.7419998645782471、0.3839998245239258、0.3900001049041748
多进程并发性能测试
之后,测试多进程并发执行CPU密集操作所需的时间。
counts = []
t = time.time()
for x in range(10):
process = Process(target=count, args=(1,1))
counts.append(process)
process.start()
e = counts.__len__()
while True:
for th in counts:
if not th.is_alive():
e -= 1
if e <= 0:
break
print("Multiprocess cpu", time.time() - t)
Output: 54.342000007629395、53.437999963760376
接着,测试多进程并发执行IO密集型操作的情况。
t = time.time()
ios = []
t = time.time()
for x in range(10):
process = Process(target=io)
ios.append(process)
process.start()
e = ios.__len__()
while True:
for th in ios:
if not th.is_alive():
e -= 1
if e <= 0:
break
print("Multiprocess IO", time.time() - t)
Output: 12.509000062942505、13.059000015258789
最后,测试多进程并发执行Http请求密集型操作的情况。
t = time.time()
httprs = []
t = time.time()
for x in range(10):
process = Process(target=http_request)
ios.append(process)
process.start()
e = httprs.__len__()
while True:
for th in httprs:
if not th.is_alive():
e -= 1
if e <= 0:
break
print("Multiprocess Http Request", time.time() - t)
Output: 0.5329999923706055、0.4760000705718994
实验结果分析与建议
基于上述实验数据,我们得出以下结果分析。
| CPU密集型操作 | IO密集型操作 | 网络请求密集型操作 | |
|---|---|---|---|
| 线性操作 | 94.91824996469 | 22.46199995279 | 7.3296000004 |
| 多线程操作 | 101.1700000762 | 24.8605000973 | 0.5053332647 |
| 多进程操作 | 53.8899999857 | 12.7840000391 | 0.5045000315 |
通过对比各组数据,我们可以观察到:
多线程在IO密集型操作中并未展现出巨大的优势(若IO任务更加繁重,优势可能会更明显);在CPU密集型操作中,其性能明显低于单线程线性执行;然而,对于网络请求这种涉及忙等阻塞的操作,多线程的优势则非常显著。
多进程在CPU密集型、IO密集型以及网络请求密集型(常发生线程阻塞的操作)场景中,均能体现出性能优势。值得注意的是,在类似网络请求密集型的操作上,多进程与多线程的性能相差无几,但多进程会占用更多的CPU等资源。因此,对于网络请求密集型场景,选择多线程执行可能是更资源友好的方案。
以上是对Python单线程、多线程和多进程效率对比的详细介绍与整合,希望能为读者提供帮助。如有任何疑问,欢迎留言,小编会及时回复。在此感谢大家对本站网站的支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













