Python Forum
efficiency of CPython expression comppilation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
efficiency of CPython expression comppilation
#1
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 ...
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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
>>> 
Gribouillis and Skaperen like this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how hard would it be to integrate CPython in a web browser? Skaperen 1 1,170 Feb-19-2023, 02:15 PM
Last Post: snippsat
  CPython ruuntime codes Skaperen 2 2,147 Feb-14-2021, 08:50 PM
Last Post: Skaperen
  Guido van Rossum about starting contributing to CPython buran 0 2,324 Feb-18-2020, 04:44 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020