<div dir="ltr">Hello all,<div><br></div><div>I have a question about the performance of broadcasting versus Python for loops. I have the following sample code that approximates some simulation I'd like to do:</div><div><br></div><div>## Test Code ##</div><div><p style="margin:0px">import numpy as np</p>
<p style="margin:0px"><br></p>
<p style="margin:0px">def lorentz(x, pos, inten, hwhm):</p>
<p style="margin:0px">    return inten*( hwhm**2 / ( (x - pos)**2 + hwhm**2 ) )</p>
<p style="margin:0px"><br></p>
<p style="margin:0px">poss = np.random.rand(100)</p>
<p style="margin:0px">intens = np.random.rand(100)</p>
<p style="margin:0px">xs = np.linspace(0,10,10000)</p>
<p style="margin:0px"><br></p>
<p style="margin:0px">def first_try():</p>
<p style="margin:0px">    sim_inten = np.zeros(xs.shape)</p>
<p style="margin:0px">    for freq, inten in zip(poss, intens):</p>
<p style="margin:0px">        sim_inten += lorentz(xs, freq, inten, 5.0)</p><p style="margin:0px">    return sim_inten</p>
<p style="margin:0px"><br></p>
<p style="margin:0px">def second_try():</p>
<p style="margin:0px">    sim_inten2 = lorentz(xs.reshape((-1,1)), poss, intens, 5.0)</p>
<p style="margin:0px">    sim_inten2 = sim_inten2.sum(axis=1)</p><p style="margin:0px">    return sim_inten2</p><p style="margin:0px"><br></p><p style="margin:0px">print np.array_equal(first_try(), second_try())<br></p><p style="margin:0px"><br></p><p style="margin:0px">## End Test ##</p><p style="margin:0px"><br></p><p style="margin:0px">Running this script prints "True" for the final equality test. However, IPython's %timeit magic, gives ~10 ms for first_try and ~30 ms for second_try. I tried this on Windows 7 (Anaconda Python) and on a Linux machine both with Python 2.7 and Numpy 1.8.2.</p><p style="margin:0px"><br></p><p style="margin:0px">I understand in principle why broadcasting should be faster than Python loops, but I'm wondering why I'm getting worse results with the pure Numpy function. Is there some general rules for when broadcasting might give worse performance than a Python loop?</p><p style="margin:0px"><br></p><p style="margin:0px">Thanks</p><p style="margin:0px"><br></p><p style="margin:0px">Ryan</p><p style="margin:0px"><br></p></div></div>