0% found this document useful (0 votes)
4 views1 page

Vectorization Performance Comparison

The document presents three methods for calculating the dot product of two vectors: a for loop, list comprehension, and a vectorized approach using NumPy. Performance measurements indicate that the vectorized method is significantly faster, taking only 14.5 µs per loop compared to 38.7 ms and 32.3 ms for the other two methods. This demonstrates the efficiency of vectorization in numerical computations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Vectorization Performance Comparison

The document presents three methods for calculating the dot product of two vectors: a for loop, list comprehension, and a vectorized approach using NumPy. Performance measurements indicate that the vectorized method is significantly faster, taking only 14.5 µs per loop compared to 38.7 ms and 32.3 ms for the other two methods. This demonstrates the efficiency of vectorization in numerical computations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

L03 - Vectorization Example

import numpy as np

def forloop(x, w):


z = 0.
for i in range(len(x)):
z += x[i] * w[i]
return z

def listcomprehension(x, w):


return sum(x_i*w_i for x_i, w_i in zip(x, w))

def vectorized(x, w):


return x_vec.dot(w_vec)

x, w = [Link](100000), [Link](100000)
x_vec, w_vec = [Link](x), [Link](w)

%timeit -r 100 -n 10 forloop(x, w)

38.7 ms ± 2.34 ms per loop (mean ± std. dev. of 100 runs, 10 loops each)

%timeit -r 100 -n 10 listcomprehension(x, w)

32.3 ms ± 1.81 ms per loop (mean ± std. dev. of 100 runs, 10 loops each)

%timeit -r 100 -n 10 vectorized(x_vec, w_vec)

The slowest run took 13.50 times longer than the fastest. This could mean that an intermediate result is being c
ached.
14.5 µs ± 7.73 µs per loop (mean ± std. dev. of 100 runs, 10 loops each)

Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/[Link]

You might also like