Python整数除法运算符vs math.floor

deC*_*sto 2 python python-3.x

使用整数除法运算符而不是math.floor对性能有任何好处吗?

7 // 2
Run Code Online (Sandbox Code Playgroud)

过度

math.floor(7/2)
Run Code Online (Sandbox Code Playgroud)

Tig*_*kT3 7

整数除法比math.floor函数调用快得多:

>>> import timeit
>>> timeit.timeit('7//2')
0.024671780910702337
>>> timeit.timeit('floor(7/2)', setup='from math import floor')
0.27053647879827736
>>> timeit.timeit('math.floor(7/2)', setup='import math')
0.3131167508719699
Run Code Online (Sandbox Code Playgroud)

正如你可以用这个拆卸看到,使用math模块的floor功能(与import mathmath.floorfrom math import floorfloor)涉及额外的查找和函数调用在平原整数除法:

>>> import dis
>>> import math
>>> from math import floor
>>> def integer_division():
...     7//2
...
>>> def math_floor():
...     floor(7/2)
...
>>> def math_full_floor():
...     math.floor(7/2)
...
>>> dis.dis(integer_division)
  2           0 LOAD_CONST               3 (3)
              3 POP_TOP
              4 LOAD_CONST               0 (None)
              7 RETURN_VALUE
>>> dis.dis(math_floor)
  2           0 LOAD_GLOBAL              0 (floor)
              3 LOAD_CONST               3 (3.5)
              6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE
>>> dis.dis(math_full_floor)
  2           0 LOAD_GLOBAL              0 (math)
              3 LOAD_ATTR                1 (floor)
              6 LOAD_CONST               3 (3.5)
              9 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             12 POP_TOP
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)

  • 您的比较并不是特别有意义,因为正如您所看到的,Python 编译器已用预先计算的常量替换了任何实际的除法逻辑。考虑使用函数参数作为被除数和除数。此外,反汇编不会告诉任何有关 VM 命令的运行时间的信息。 (2认同)