In python, which one is faster ?
numpy.max(), numpy.min()
or
max(), min()
My list/array length varies from 2 to 600. Which one should I use to save some run time ?
maximum() function is used to find the element-wise maximum of array elements. It compares two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned.
Because the Numpy array is densely packed in memory due to its homogeneous type, it also frees the memory faster. So overall a task executed in Numpy is around 5 to 100 times faster than the standard python list, which is a significant leap in terms of speed.
Find maximum value & its index in a 1D Numpy Array:amax() to find the maximum value from this numpy array by passing just array as argument i.e. Find index of maximum value : Get the array of indices of maximum value in numpy array using numpy.
Return the maximum of an array or maximum along an axis.
Well from my timings it follows if you already have numpy array a
you should use a.max
(the source tells it's the same as np.max
if a.max
available). But if you have built-in list then most of the time takes converting it into np.ndarray => that's why max
is better in your timings.
In essense: if np.ndarray
then a.max
, if list
and no need for all the machinery of np.ndarray
then standard max
.
I was also interested in this and tested the three variants with perfplot (a little project of mine). Result: You're not going wrong with a.max()
.
Code to reproduce the plot:
import numpy as np import perfplot b = perfplot.bench( setup=np.random.rand, kernels=[max, np.max, lambda a: a.max()], labels=["max(a)", "np.max(a)", "a.max()"], n_range=[2 ** k for k in range(25)], xlabel="len(a)", ) b.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With