Python Forum
efficiency of CPython expression comppilation - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: efficiency of CPython expression comppilation (/thread-36004.html)



efficiency of CPython expression comppilation - Skaperen - Jan-09-2022

i need to divide a number which is a long duration in seconds by the number of seconds in a week (604800) to get the number of weeks. if i were to write the code as an expression of literal constants like 7*24*60*60, would CPython compile this as 604800 so only the divide is done at run time? does it always compile and reduce constant expressions as if given as a literal?

the choice of seconds in a week is just one use case. for this division i may be using divmod(). the purpose of writing the code this way is to show the components of the numbers which many people will not immediately recognize (if ever). IMHO, more people will understand w=delta/(7*24*60*60) than w=delta/604800. but if i do that deep in a busy loop ...


RE: efficiency of CPython expression comppilation - casevh - Jan-09-2022

Python does perform constant expression optimizations. The dis (short for disassemble) module can show it in action.

>>> def f(x):
...   return x/(7*24*60*60)
... 
>>> import dis
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (x)
              2 LOAD_CONST               1 (604800)
              4 BINARY_TRUE_DIVIDE
              6 RETURN_VALUE
>>>