Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy clip function takes twice as long as expected

Tags:

python

numpy

clip

I'm finding that the performance of the numpy clip function is significantly slower than just doing it myself with a mask (164us vs about 74us). Is the clip function doing something additional that makes it take twice as long?

%timeit growth.clip(-maxg, maxg)
10000 loops, best of 3: 164 µs per loop

%timeit growth[np.greater(growth,maxg)] = maxg
10000 loops, best of 3: 37.1 µs per loop

%timeit growth[np.less(growth,-maxg)] = -maxg
10000 loops, best of 3: 37 µs per loop

After resetting the growth array and testing in the opposite order:

%timeit growth[np.less(growth,-maxg)] = -maxg
10000 loops, best of 3: 36.6 µs per loop

%timeit growth[np.greater(growth,maxg)] = maxg
10000 loops, best of 3: 37.3 µs per loop

%timeit growth.clip(-maxg, maxg)
100 loops, best of 3: 150 µs per loop

Note that growth is a fairly big array:

growth.shape
(12964, 7)
like image 454
tim654321 Avatar asked Sep 10 '15 03:09

tim654321


People also ask

What does NP clip () do?

clip() function is used to Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.

How do I clip values in a NumPy array?

To limit the values of the NumPy array ndarray to given range, use np. clip() or clip() method of ndarray . By specifying the minimum and maximum values in the argument, the out-of-range values are replaced with those values. This is useful when you want to limit the values to a range such as 0.0 ~ 1.0 or 0 ~ 255 .


1 Answers

The default numpy.clip returns a new array with the clipped values. Using the argument out=growth makes the operation in-place:

growth.clip(-maxg, maxg, out=growth)

This way, the time taken by clip is more similar to the alternative that you mentioned.

like image 75
YS-L Avatar answered Sep 18 '22 13:09

YS-L