我已经阅读了有关 GIL 的精彩介绍: http://www.dabeaz.com/python/UnderstandingGIL.pdf
Dave 在这里说,自从 Python3.2 以来,我们有了新的更好的 GIL 版本,并提供了证明这一点的示例(在幻灯片 54 上)。
但是当我自己在 Python 3.4 上测试它们时,性能似乎更差:
from threading import Thread
def count(n):
while n > 0:
n -= 1
def sequential_test():
count(100000000)
count(100000000)
def threaded_test():
t1 = Thread(target=count,args=(100000000,))
t1.start()
t2 = Thread(target=count,args=(100000000,))
t2.start()
t1.join()
t2.join()
所以在我的 Linux 双核笔记本电脑上 在 Python 2.7 中我得到:
sequential_test: 11s
threaded_test: 17s
在 Python 3.4 中我得到:
sequential_test: 18s
threaded_test: 28s
所以问题是,为什么在 Python 3.4 中,在这两种情况下,代码运行速度都较慢,以及为什么与 Python2 相比,我没有看到 GIL 在两个受 CPU 限制的进程上有任何改进?
可能是我做错了什么?
我的猜测是,在 Python2 中,对此类代码进行了一些 C 代码优化,这就是它运行速度更快的原因,但我对此一无所知
请您参考如下方法:
我测试了这个循环:
for (i=0; i<loops; i++)
{
Py_BEGIN_ALLOW_THREADS
Py_END_ALLOW_THREADS
}
在 Centos 7、i7-2600 上循环设置为 10,000,000
python 2.7 真实的 0m0.199s 用户 0m0.109s 系统 0m0.011s
python 3.7 真正的 0m0.912s 用户 0m0.791s 系统 0m0.009s
2.7 快了将近 8 倍(CPU 时间)
