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.

Community
  • 1
  • 1
Mathias711
  • 6,568
  • 4
  • 41
  • 58
  • 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`](https://docs.python.org/2/library/timeit.html) module for this. – luk32 Apr 10 '14 at 08:54
  • The first code snippet is 4.47us versus 11.9us but I would profile it using your real data – EdChum Apr 10 '14 at 08: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 – EdChum Apr 10 '14 at 09: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! – Mathias711 Apr 10 '14 at 09:01

1 Answers1

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

EdChum
  • 376,765
  • 198
  • 813
  • 562