Math optimization

David Lees debl2nononspammmy at bellatlantic.net
Sat Sep 21 19:51:16 EDT 2002


Using the quick and dirty code below and just changing line 9 between
prod = n * b and prod = n*7, running on my Win98SE, Python 2.2.1 I get a
13% difference between using a constant and a variable.  I don't know
much about what Python is doing in the way of optimization or if it is
even keeping things as integer arithmetic, so take it with a grain of
salt.

David Lees



import time,string

n = string.atoi(sys.argv[1])
total = n
prod = 1
b = 7
t0 = time.clock()
while (n):
   prod = n*b
   n -= 1
t1 = time.clock()

n=total
t2 = time.clock()
while (n):
   pass
   n -= 1    
t3 = time.clock()

A = t1-t0
B = t3-t2

print total, A-B

David Lees wrote:
> 
> This depends on your hardware, OS and probably Python version. Further
> you need to specify the data type.  Integer, floating point or infinite
> precision integers.  It is quite easy to run benchmarks, which you
> should do yourself.
> 
> David Lees
> 
> Zed wrote:
> >
> > Hi!
> > What's faster in python? Divide or multiply?
> > (a= b*c  is faster than   a=b/c)?
> >
> > Math expressions with constants are calcolated during .pyc creation or real
> > time?
> > (a=b*5   is faster than    a=b*5*2/2 )?
> >
> > Thanks



More information about the Python-list mailing list