Use of Numpy to increase efficiency

Use of Numpy to increase efficiency

Speeding up your python programming by using NumPy:

Many times there are requirements where we need to iterate millions or more times to get a particular output and the most common way is using "for loops".

But "for loops" takes a lot of time, so to increase the speed of your code we can use NumPy operations wherever possible. For example:

Suppose I have two arrays of 1 million integers each and I need to add the same so one way is to use for loop and iterate over it 1 million times. Here I am initializing two arrays a and b with 1 million random integers.

No alt text provided for this image

First, we will use the for loop to check the time taken

No alt text provided for this image

So it takes about 456 milliseconds to give the output. Next, we will use NumPy's dot product to get the sum for the same array.

No alt text provided for this image

Woah!! It just took 0.852 milliseconds to give the same output. Numpy operations are much faster as they are implemented in C and are able to divide the task into multiple sub-tasks and process them parallelly.

A "for loop" can't be entirely removed but whenever possible try to use NumPy or inbuilt functions.







To view or add a comment, sign in

Explore content categories