multiply each element of a list by a number

skip at pobox.com skip at pobox.com
Mon Dec 29 07:30:21 EST 2008


>>>>> "Colin" == Colin J Williams <cjw at ncf.ca> writes:

    Colin> skip at pobox.com wrote:

    >> For extremely short lists, but not for much else:
    >> 
    >> % for n in 1 10 100 1000 10000 100000 ; do
    >> >   echo "len:" $n
    >> >   echo -n "numpy: "
    >> >   python -m timeit -s 'import numpy ; a = numpy.array(range('$n'))' 'a*3'
    >> >   echo -n "list: "
    >> >   python -m timeit -s 'a = range('$n')' '[3*x for x in a]'
    >> > done
    >> len: 1
    >> numpy: 100000 loops, best of 3: 11.7 usec per loop
    >> list: 1000000 loops, best of 3: 0.698 usec per loop
    >> len: 10
    >> numpy: 100000 loops, best of 3: 11.7 usec per loop
    >> list: 100000 loops, best of 3: 2.94 usec per loop
    >> len: 100
    >> numpy: 100000 loops, best of 3: 12.1 usec per loop
    >> list: 10000 loops, best of 3: 24.4 usec per loop
    >> len: 1000
    >> numpy: 100000 loops, best of 3: 15 usec per loop
    >> list: 1000 loops, best of 3: 224 usec per loop
    >> len: 10000
    >> numpy: 10000 loops, best of 3: 41 usec per loop
    >> list: 100 loops, best of 3: 2.17 msec per loop
    >> len: 100000
    >> numpy: 1000 loops, best of 3: 301 usec per loop
    >> list: 10 loops, best of 3: 22.2 msec per loop
    >> 
    >> This is with Python 2.4.5 on Solaris 10.  YMMV.

    Colin> Your comment is justified for len= 100 
    Colin> or 1,000 but not for len= 10,000 or 100,000.

Look again at the time units per loop.

    Colin> I wonder about the variability of the number of loops in your
    Colin> data.

That's how timeit works.  It runs a few iterations to see how many to run to
get a reasonable runtime.

    Colin> I have tried to repeat your test with the program below, but it
    Colin> fails to cope with numpy.

I stand by my assertion that numpy will be much faster than pure Python for
all but very short lists.

-- 
Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/



More information about the Python-list mailing list