Ask Your Question

Speedup commonly used Sage functions?

asked 2010-10-23 00:16:20 -0500

roland gravatar image

updated 2011-04-28 10:04:26 -0500

Kelvin Li gravatar image


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]



>>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 flag offensive close merge delete

3 answers

Sort by » oldest newest most voted

answered 2010-10-24 13:41:43 -0500

mhampton gravatar image

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.

edit flag offensive delete link more

answered 2010-10-25 07:44:07 -0500

roland gravatar image

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

def test2():

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



625 loops, best of 3: 1.22 ms per loop

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

edit flag offensive delete link more

answered 2010-10-25 08:30:59 -0500

mhampton gravatar image

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):
    answer = []
    for k1 in xrange(nx):
        for k2 in xrange(nx):
            for k3 in xrange(nx): answer.append([k1,k2,k3])
    return answer

the xmrange solution wins:

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

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

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

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2010-10-23 00:16:20 -0500

Seen: 504 times

Last updated: Oct 25 '10