Numpy methods to calculate the sum or product of two vectors for element wise are faster than the normal unvectorized code implementation using loops and iterating over the arrays. Be that, I want to know the under hood process that takes place in the vectorized numpy method.
For example:
The code below gives the dot product of two same dimensional array.First, iteration method is used.Then the vectorized numpy method is used.
Fascinatingly, the time of execution for normal iterative process is around **35ms** and for numpy method is around 0.2ms.
Take a look at the code……..
# Dot product
import time
import numpy
import array
# 8 bytes size int
a = array.array('q')
for i in range(100000):
a.append(i);
b = array.array('q')
for i in range(100000, 200000):
b.append(i)
# classic dot product of vectors implementation
tic = time.process_time()
dot = 0.0;
for i in range(len(a)):
dot += a[i] * b[i]
toc = time.process_time()
#using numpy method
n_tic = time.process_time()
n_dot_product = numpy.dot(a, b)
n_toc = time.process_time()
So my doubt is that what happens internally at the processor level when numpy code is implemented and normal code is implemented.
How come elements are accessed from arrays without iteration in case of numpy?
shree is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.