Vectorization using Python

Brief on Vectorization

Vectorization is basically used to speed up Python programming by avoiding loops as much as possible in the code. A lot of operations can be performed using vectorization such as dot product of vectors or even element wise multiplication.

Vectorization is generally termed as SIMD (single instruction, multiple data).

More details are here “Why Vectorization is faster than Loops”

Sample Python code

import time 
import numpy 
import array 
  
## Define the 2 arrays
a = array.array('q') 
for i in range(10000000): 
    a.append(i); 
  
b = array.array('q') 
for i in range(10000000, 20000000): 
    b.append(i) 
  
start_time = time.process_time() 
dot = 0.0; 

## Use For loop to perfrom Dot product
for i in range(len(a)): 
      dot += a[i] * b[i] 
  
end_time = time.process_time() 
  
print("For Loop Computation time = " + str(1000*(end_time - start_time )/60) + " sec") 
   
## Vectorization

start_time = time.process_time() 
numpy.dot(a, b) 
end_time = time.process_time() 
  
print("Vectorization Computation time = "+str(1000*(end_time - start_time )/60)+" sec") 

Computation time between For loops vs Vectorization

For Loop (Computation time) = 48.958333333333336 sec

Vectorization (Computation time) = 0.2604166666666667 sec

More interesting reads Vectorization from GeeksfromGeeks

Vectorization is way faster than Loops !!