On Sun, Dec 19, 2004 at 03:04:15AM -0800, Rahul wrote: > HI. > I want to compute dot product of two vectors stored as lists a and b.a > and b are of the same length. > > one simple way is > sum(a[i]*b[i] for i in range(len(a))) > > another simple way is > ans=0.0 > for i in range(len(a)): > ans=ans+a[i]*b[i] > > But is there any other way which is faster than any of the above. (By > the way profiling them i found that the second is faster by about 30%.) > rahul
some numbers to confirm my previous reply: 1 zip: 0.00115 (1.00) range: 0.00108 (0.94) array: 0.00075 (0.65) 10 zip: 0.00306 (1.00) range: 0.00288 (0.94) array: 0.00074 (0.24) 100 zip: 0.02195 (1.00) range: 0.02035 (0.93) array: 0.00079 (0.04) 1000 zip: 0.21016 (1.00) range: 0.19930 (0.95) array: 0.00130 (0.01) 10000 zip: 4.98902 (1.00) range: 2.70843 (0.54) array: 0.01405 (0.00) (the integers are the number of elements in a random array of floats; 'zip' refers to sum([x*y for (x,y) in zip(a,b)]) 'range', to sum([a[i]*b[i] for i in range(len(a))]) and 'array' makes a and b Numeric's 'array' objects, with atlas installed (and hence dotblas loading and assembler version of dot tuned for the system's processor (in this case a pentium3)). The code in this case is simply Numeric.dot(a, b) The advantage of atlas on systems with sse2 should be even greater. -- John Lenton ([EMAIL PROTECTED]) -- Random fortune: El deseo nos fuerza a amar lo que nos hará sufrir. -- Marcel Proust. (1871-1922) Escritor francés.
signature.asc
Description: Digital signature
-- http://mail.python.org/mailman/listinfo/python-list