constant in python?

Alex Martelli aleaxit at yahoo.com
Sat Aug 18 12:59:30 EDT 2001


"Michael Ströder" <michael at stroeder.com> wrote in message
news:3B7E5355.675D569B at stroeder.com...
> Alex Martelli wrote:
> >
> > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207
> >
> > If something can be done with a few lines of code in the
> > language as it is, it requires very strong motivation for that
> > something to become a built-in language mechanism:
>
> I would guess that the recipe above causes some performance penalty.

Why guess, when you can measure?

Say const.py is like in the recipe, normal.py is an empty
normal module, and test.py contains:

import time, const, normal

start = time.clock()
const.magic = 23
sum = 0L
for i in range(100000):
    sum += const.magic
stend = time.clock()

print "const : %5.2f"%(stend-start)

start = time.clock()
normal.magic = 23
sum = 0L
for i in range(100000):
    sum += normal.magic
stend = time.clock()

print "normal: %5.2f"%(stend-start)

Here are three runs on my box:

D:\ian\good>python test.py
const :  1.44
normal:  1.60

D:\ian\good>python test.py
const :  1.63
normal:  1.53

D:\ian\good>python test.py
const :  1.41
normal:  1.53

See?  No statistically significant difference penalizes the
const module vs a normal module -- it so happens the
loop using the const module was faster two times out
of three, but this is indeed happenstance.

Moral: never guess at performance -- it often baffles the
intuition even of the most accomplished expert.  MEASURE.


> > I think that "constants" are a good
> > example of something that should NOT be in the language
> > itself, exactly because it's a minor issue and it can be
> > easily implemented without too much trouble
>
> Disclaimer: I'm not a compiler expert.
> IMHO constants are useful in compiled languages because they are
> immutable and therefore a compiler can insert them as "in-line"
> operands for optimization.

Sure, no doubt you can gain a microsecond or two each
time a constant is a literal rather than having to be fetched
anew from the module owning it.  But, so what?!  Any
good Python developer using a module attribute (that is
not meant to change) in a tight loop that'a performance
hot-spot would surely 'hoist' the module access out of
the loop, using a local function variable instead (which
is just as fast to access as a literal).

Don't guess -- MEASURE: change the above program to
consider literals and hoisting too: and see what comes up...

The design of the Python language is *NOT* traditionally
driven by an obsession with micro-optimizations -- thanks
be, or it would most definitely _NOT_ be Python.  These
misplaced performance-related worries surely can't justify
perverting the language by adding a built-in "constant".


Alex






More information about the Python-list mailing list