为什么在 python 2.7 和 python 3.4 性能中创建类之间存在差异 [英] Why there's the difference between creating class in python 2.7 and python 3.4 performance

查看:49
本文介绍了为什么在 python 2.7 和 python 3.4 性能中创建类之间存在差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from timeit import Timer as T

def calc(n):
    return T("class CLS(object): pass").timeit(n)

print(calc(90000))
print(calc(90000))
print(calc(90000))

# python3.4
1.1714721370008192
1.0723806529986177
1.111804607000522

# python2.7
15.7533519268
16.7191421986
16.8397979736

为什么使用不同版本的python在类创建时间上会有如此大的差异?在同一台机器上测试:

Why is there so much difference in class creation time using different versions of python? Tested on the same machine:

  • i5-3450 CPU @ 3.10GHz
  • 8GB 内存

推荐答案

timeit 禁用垃圾收集器,否则会破坏使类对象保持活动状态的循环.因此,在 timeit 完成之前,不会释放任何类.

timeit disables the garbage collector, which would otherwise break the cycles that keep a class object alive. Thus none of the classes gets deallocated until after timeit has finished.

object.__subclasses__() 通过弱引用的内部集合引用这些类.tp_subclasses 旧的基于列表的实现每次都会搜索整个列表以找到可以替换的死引用.对于每个额外的子类,此过程需要更多时间.另一方面,3.4中新的基于dict的设计可以在恒定时间内添加一个引用.请参阅问题 17936.

object.__subclasses__() references these classes via an internal collection of weak references. The old list-based implementation of tp_subclasses searches the entire list each time to find a dead reference that can be replaced. This process takes more time with each additional subclass. On the other hand, the new dict-based design in 3.4 can add a reference in constant time. See issue 17936.

感谢 @MichaelYounkin 指出这在 3.2 中也很慢.最初我试图将性能差异缩小到 2.x 和 3.x 之间小对象分配器的变化,但在阅读他的评论后,我发现即使是 3.3 也比 3.4 慢得多.所以我浏览了 typeobject.c filelog 以查看最近的变化.

Thanks to @MichaelYounkin for pointing out how this is also slow in 3.2. Initially I tried to narrow the performance difference to a change in the small-object allocator between 2.x and 3.x, but after reading his comment I discovered that even 3.3 was considerably slower than 3.4. So I scanned over the typeobject.c filelog to review recent changes.

这篇关于为什么在 python 2.7 和 python 3.4 性能中创建类之间存在差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆