Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.max or max ? Which one is faster?

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 ?

like image 543
Froyo Avatar asked Jun 08 '12 04:06

Froyo


People also ask

What is Numpy maximum?

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.

How fast is Numpy Where?

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.

How does Numpy calculate Max?

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.

What is NP Amax return?

Return the maximum of an array or maximum along an axis.


2 Answers

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.

like image 194
gorlum0 Avatar answered Oct 06 '22 20:10

gorlum0


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().

enter image description here

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() 
like image 32
Nico Schlömer Avatar answered Oct 06 '22 19:10

Nico Schlömer