3

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.

4
  • You can make up an example consisting from like 10^6 vectors and check. Or run it in a loop. There is even a timeit module for this. Commented Apr 10, 2014 at 8:54
  • The first code snippet is 4.47us versus 11.9us but I would profile it using your real data Commented Apr 10, 2014 at 8:55
  • 2
    Actually there appears to be no difference in the timings, for a random array of 100,000 elements it takes 51.2us just to calculate P=H.max() then 165 us for SP = P*np.array(S) and then 217us for SP = H.max()*np.array(S) so there is little difference Commented Apr 10, 2014 at 9:00
  • @EdChum okay. I have been trying with timeit myself, but I never done it before, so I couldnt get it tested as fast as you did it. Thanks for the info! Commented Apr 10, 2014 at 9:01

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.