自Python3.2以来GIL的实现是否变得更糟?

时间:2016-03-20 18:28:05

标签: python performance gil

我已经阅读了关于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中两种情况下代码运行速度较慢以及为什么我认为两个CPU绑定进程的GIL与Python2相比没有任何改进?

可能是我做错了什么?

我的猜测是,在Python2中有一些代码优化的C代码,这就是为什么它的工作速度更快,但我没有它的优点

1 个答案:

答案 0 :(得分:-1)

我测试了这个循环:

    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 sys 0m0.011s

Python 3.7 真正的0m0.912s 用户0m0.791s sys 0m0.009s

2.7快了近8倍(CPU时间)