multiply each element of a list by a number

skip at pobox.com skip at pobox.com
Sun Dec 28 00:06:06 CET 2008


    Colin> ... perhaps faster than numpy:
    ...

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.

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



More information about the Python-list mailing list