Math optimization

jepler at unpythonic.net jepler at unpythonic.net
Sat Sep 21 23:01:11 EDT 2002


... and your results will change again if you work at function scope, not
global scope.  Lookups of locals or constants are faster than lookups of globals.

I still doubt you'll measure a substantial difference between * and / on
ints, though.  I am getting 1.94 vs 2.08 seconds on 1,000,000 iterations,
which is actually bigger than I expected.

Comparing a*b to a*3 (and likewise for division) also surprised me:  a*b is
faster in function scope (and likewise for division).

If you are planning to do a lot of operations of this kind, for instance on
long lists, then what you're actually looking for is the "Numeric"
extension, which can perform these tasks at C speeds.

Jeff

r = range(1000000)

def f(x):
    for i in r:
	res = x * 3

def g(x):
    for i in r:
	res = x / 3

def h(x):
    for i in r:
	pass

def j(x, y):
    for i in r:
	res = x * y

def k(x, y):
    for i in r:
	res = x / y

import time

for fun in (f, g, h):
    t0 = time.time()
    fun(7)
    t1 = time.time()
    print fun.__name__, t1-t0 

for fun in (j, k):
    t0 = time.time()
    fun(7, 3)
    t1 = time.time()
    print fun.__name__, t1-t0 




More information about the Python-list mailing list