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.
First, we will use the for loop to check the time taken
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.
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.