简体   繁体   中英

Variable lookup: Why is ** with variables so much slower than with values

I've read about math.sqrt being faster than ** and today I tried. But the interesting thing wasn't the time difference between those two but the time difference between ** with variables and ** with values:

value1 = 10.1
value2 = 0.5
%timeit value1 ** value2
# 1000000 loops, best of 3: 645 ns per loop
%timeit 10.1 ** 0.5
# 10000000 loops, best of 3: 60.7 ns per loop

This is more than ten times faster. While for the math-function the timings are almost identical (only few ns more for the variable lookup):

import math
%timeit math.sqrt(10.1)
# 1000000 loops, best of 3: 529 ns per loop
%timeit math.sqrt(value1)
# 1000000 loops, best of 3: 568 ns per loop

Could anyone explain why the variable lookup makes such a huge difference for ** while it makes little difference for math.sqrt ?

Setting:

  • python 3.5
  • Windows 10 64 bit

Using variables:

In [41]: def var():
   ....:     value1 ** value2
   ....:     

In [43]: dis.dis(var)
  2           0 LOAD_GLOBAL              0 (value1)
              3 LOAD_GLOBAL              1 (value2)
              6 BINARY_POWER
              7 POP_TOP
              8 LOAD_CONST               0 (None)
             11 RETURN_VALUE

Using immediate values:

In [44]: def imm():
   ....:     10.1 ** 0.5
   ....:     

In [45]: dis.dis(imm)
  2           0 LOAD_CONST               3 (3.1780497164141406)
              3 POP_TOP
              4 LOAD_CONST               0 (None)
              7 RETURN_VALUE

Turns out that the compiler outsmarted us and calculated the power beforehand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM