# Speedup commonly used Sage functions?

Hi,

Sage has many nice shorthand functions. This makes programming easy (to read, to debug). But it comes with a price! For instance:

def test1():

for k in xmrange([100]*3): return k

def test2():

for k1 in xrange(100):
for k2 in xrange(100):
for k3 in xrange(100):
return [k1,k2,k3]

timeit('test1()')

timeit('test2()')

>>625 loops, best of 3: 45.9 µs per loop
>>625 loops, best of 3: 1.59 µs per loop


## Four questions:

• Can we inform users that "it comes with a price?"

• Can we speed up common, often used functions (easily)?

• For more advanced users, can we provide them with a Cython equivalent? (named for instance cxmrange)

• Maybe there is a better approach I'm not aware of?
edit retag close merge delete

Sort by » oldest newest most voted

OK, that makes more sense. But for some purposes, xmrange is faster. Suppose you actually want the output of xmrange as a list. Then if you look at:

def test1(nx):
return xmrange([nx]*3)

def test2(nx):
for k1 in xrange(nx):
for k2 in xrange(nx):
for k3 in xrange(nx): answer.append([k1,k2,k3])


the xmrange solution wins:

timeit('test1(10)')
625 loops, best of 3: 28.5 µs per loop

timeit('test2(10)')
625 loops, best of 3: 403 µs per loop


although I'm sure there are more efficient ways to use xrange for this.

more

Oeps! Apologies for any inconvenience caused.

I typed the examples above.... not a good idea. Still the point raised is valid.

def test1():
for k in xmrange([10]*3): k
return

def test2():

for k1 in xrange(10):
for k2 in xrange(10):
for k3 in xrange(10): [k1,k2,k3]
return


timeit('test1()')

timeit('test2()')

625 loops, best of 3: 1.22 ms per loop

625 loops, best of 3: 256 µs per loop

more

Those two functions don't really do the same thing. They both return [0,0,0], so if that's all you want you could do:

def test3():
return [0,0,0]


The function test1 is probably slower because it has to actually construct an object to iterate over those values, while test2 does not. It might be more fair to compare functions that return all the values.

more