Mathias711
Mathias711

Reputation: 6668

Multiplying array in python

From this question I see how to multiply a whole numpy array with the same number (second answer, by JoshAdel). But when I change P into the maximum of a (long) array, is it better to store the maximum on beforehand, or does it calculate the maximum of H just once in the second example?

import numpy as np
H = [12,12,5,32,6,0.5]
P=H.max()
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)

or

import numpy as np
H = [12,12,5,32,6,0.5]
S=[22, 33, 45.6, 21.6, 51.8]
SP = H.max()*np.array(S)

So does it calculate H.max() for every item it has to multiply, or is it smart enough to it just once? In my code S and H are longer arrays then in the example.

Upvotes: 3

Views: 1191

Answers (1)

EdChum
EdChum

Reputation: 394439

There is little difference between the 2 methods:

In [74]:

import numpy as np
H = np.random.random(100000)
%timeit P=H.max()
S=np.random.random(100000)
%timeit SP = P*np.array(S)
%timeit SP = H.max()*np.array(S)
10000 loops, best of 3: 51.2 µs per loop
10000 loops, best of 3: 165 µs per loop
1000 loops, best of 3: 217 µs per loop

Here you can see that the individual step of pre-calculating H.max() is no different from calculating it in a single line

Upvotes: 3

Related Questions