Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are simple hardcoded arithmetics cached/compiled away?

I would like to know if python caches / compiles away in its .pyc files simple arithmetics like 5*5+5.

Sometimes I like to write if seconds > 24*60*60 for a day for example. I know that the effect on performance is unnoticeable but I'm curious nevertheless.

like image 334
timakro Avatar asked Mar 13 '23 21:03

timakro


1 Answers

Yes, CPython (the default implementation of Python) uses a peephole optimiser to collapse such expressions into one number; this is called constant folding.

You can check for this using the dis disassembler:

>>> import dis
>>> def foo():
...     if seconds > 24*60*60:
...         pass
...
>>> dis.dis(foo)
  2           0 LOAD_GLOBAL              0 (seconds)
              3 LOAD_CONST               4 (86400)
              6 COMPARE_OP               4 (>)
              9 POP_JUMP_IF_FALSE       15

  3          12 JUMP_FORWARD             0 (to 15)
        >>   15 LOAD_CONST               0 (None)
             18 RETURN_VALUE

Note the LOAD_CONST instruction at offset 3; it loads the final result of the 24*60*60 expression, the expression itself is gone from the bytecode.

See the fold_binops_on_constants function in the peephole.c file.

like image 187
Martijn Pieters Avatar answered Mar 31 '23 20:03

Martijn Pieters