【问题标题】:Is it possible for the Python compiler to optimize away some integer arithmetic?Python 编译器是否可以优化一些整数运算?
【发布时间】:2012-07-14 05:06:31
【问题描述】:

灵感来自 this 关于 Python 缓存小整数的问题。

Python 编译器是否可以在编译时将 (0 - 6) 替换为 -6?下面的代码表明它没有。如果不可能,为什么不呢?我不认为0-6 的含义在运行时会有所不同。

如果可以,为什么 CPython 不这样做?

# test_integers.py
def test_integers():
    print "-6 is -6 ?", -6 is -6 # True
    print "(0 - 6) is -6 ?", (0 - 6) is -6 # False

# import_test_integers.py
import test_integers
test_integers.test_integers()

我的 Python 详细信息,以防这非常依赖于实现:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2

【问题讨论】:

  • FWIW:这种类型的优化被称为“常量折叠”。 (我不知道 CPython 是否这样做。)

标签: python compiler-construction


【解决方案1】:

首先,您不应该使用is 比较整数值来检测优化。正如您链接的问题中所解释的那样,这与任何事情无关。如果您想知道对您的函数进行了哪些优化,请使用dis 模块,该模块产生(在 2.7.2 中,在修复您的 -1 错字后):

>>> import dis
>>> 
>>> def test_integers():
...     print "-6 is -6 ?", -6 is -6 # True
...     print "(0-6) is -6 ?", (0 - 6) is -6 # False
... 
>>> dis.dis(test_integers)
  2           0 LOAD_CONST               1 ('-6 is -6 ?')
              3 PRINT_ITEM          
              4 LOAD_CONST               2 (-6)
              7 LOAD_CONST               2 (-6)
             10 COMPARE_OP               8 (is)
             13 PRINT_ITEM          
             14 PRINT_NEWLINE       

  3          15 LOAD_CONST               3 ('(0-6) is -6 ?')
             18 PRINT_ITEM          
             19 LOAD_CONST               6 (-6)
             22 LOAD_CONST               2 (-6)
             25 COMPARE_OP               8 (is)
             28 PRINT_ITEM          
             29 PRINT_NEWLINE       
             30 LOAD_CONST               0 (None)
             33 RETURN_VALUE        

你会看到减法实际上被优化了。你也可以看到其他一些:

>>> def f():
...     x = 1+2
...     x = 2-3
...     x = 3*4
...     x = 4/5
...     x = 5**6
... 
>>> dis.dis(f)
  2           0 LOAD_CONST               7 (3)
              3 STORE_FAST               0 (x)

  3           6 LOAD_CONST               8 (-1)
              9 STORE_FAST               0 (x)

  4          12 LOAD_CONST               9 (12)
             15 STORE_FAST               0 (x)

  5          18 LOAD_CONST               4 (4)
             21 LOAD_CONST               5 (5)
             24 BINARY_DIVIDE       
             25 STORE_FAST               0 (x)

  6          28 LOAD_CONST              10 (15625)
             31 STORE_FAST               0 (x)
             34 LOAD_CONST               0 (None)
             37 RETURN_VALUE        

【讨论】:

  • 精氨酸。我正要发布一些关于这个效果的东西。不错的答案。 +1
  • 更正了错字,谢谢。仍在消化你剩下的答案
  • 这完美地回答了我的问题,但我现在对 LOAD_CONSTco_consts 的工作方式更加困惑。如果我无法找到或找出答案,将发布后续问题。
  • 是的,我希望我会接受它 - 只是推迟,以防有人发布更好的答案。
猜你喜欢
  • 2018-08-19
  • 2012-10-05
  • 1970-01-01
  • 2016-09-11
  • 2023-04-10
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
相关资源
最近更新 更多