Ask Your Question
1

Speedup commonly used Sage functions?

asked 2010-10-23 07:16:20 +0100

roland gravatar image

updated 2011-04-28 17:04:26 +0100

Kelvin Li gravatar image

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

3 Answers

Sort by » oldest newest most voted
0

answered 2010-10-25 15:30:59 +0100

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:

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.

edit flag offensive delete link more
0

answered 2010-10-25 14:44:07 +0100

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
    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

edit flag offensive delete link more
0

answered 2010-10-24 20:41:43 +0100

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

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 2010-10-23 07:16:20 +0100

Seen: 872 times

Last updated: Oct 25 '10