Python 编译器是否可以优化一些整数运算?

2023-12-30

灵感来自this https://stackoverflow.com/questions/11476190/why-0-6-is-6-false关于Python缓存小整数的问题。

Python编译器是否可以在编译时将(0 - 6)替换为-6?下面的代码表明事实并非如此。如果不可能,为什么不呢?我不认为这有什么意义0, -, or 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

首先,你不应该使用is比较整数值以检测优化。正如您链接的问题中所解释的,这与任何事情都无关。如果您想知道对您的函数执行了哪些优化,请使用dis http://docs.python.org/library/dis.html模块,它会产生(在 2.7.2 中,修复你的-1 typo):

>>> 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        

你会看到减法实际上was优化掉。您还可以看到其他一些:

>>> 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        
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 编译器是否可以优化一些整数运算? 的相关文章

随机推荐