cjw at ncf
Dec 28, 2008, 3:26 PM
Post #10 of 13
(67632 views)
Permalink

Re: multiply each element of a list by a number
[In reply to]


skip [at] pobox wrote: > 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, Your comment is justified for len= 100 or 1,000 but not for len= 10,000 or 100,000. I wonder about the variability of the number of loops in your data. I have tried to repeat your test with the program below, but it fails to cope with numpy. The results for Python 2.5 are: list: 0.421 0.253 list: 0.427 0.254 list: 0.420 0.250 list: 0.421 0.255 list: 0.415 0.254 list: 0.423 0.254 list: 0.422 0.256 The results for Python 2.6 are: list: 0.388 0.228 list: 0.410 0.225 list: 0.384 0.227 list: 0.389 0.226 list: 0.390 0.227 The script used above for both 2.5 and 2.6: # speedUgh.py To compare array timing ##import numpy import timeit as _t m= 100 # number of repetitions values= (10, 100) numpyRes= [] listRes= [] for n in values: sn= 'numpy.arange(' + str(n) + ')*3' t= _t.Timer(sn) ## r= t.repeat(3, m) ## numpyRes.append(sum(t.repeat(3, m)) * 1000000/(3*m*n)) sl='a= [3*k for k in range(' + str(n) + ')]' t= _t.Timer(stmt= sl) listRes.append( sum(t.repeat(3, m)) * 1000000/(3*m*n)) ##print 'numpy:', len(values)*'%8.3f' % tuple(numpyRes) print ' list:', len(values)*'%8.3f' % tuple(listRes) Colin W.  http://mail.python.org/mailman/listinfo/pythonlist
