I'm comparing methods to do calculations against large arrays and wanted to compare the speed of broadcasting operators in numpy versus alternatives. I was surprised to see the speed of the python map()
function though, and am wondering if someone could explain how this is so much faster than broadcasting.
Broadcasting
%%timeit farenheit = np.linspace( -10, 20, 1000 )
celcius = (farenheit - 32) * (5/9)
4.5 µs ± 99.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
List comprehension
%%timeit farenheit = np.linspace( -10, 20, 1000 )
[(temp - 32) * (5/9) for temp in farenheit]
886 µs ± 4.56 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Python 3 map()
%%timeit farenheit = np.linspace( -10, 20, 1000 )
celcius = map(lambda temp: (temp - 32) * (5/9), farenheit)
248 ns ± 41.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
farenheit = np.linspace( -10, 20, 1000 )
part in the timings too? For a better benchmarking (to compare NumPy vs map, etc.), think it's better to pre-process that part. – Divakar%%timeit
should exclude the array creation (whatever is on the first line is ignored). ipython.readthedocs.io/en/stable/interactive/magics.html – Christopher%%timeit
includes everything in that block. So,linspace
one is included too. – Divakar%%timeit
to precalculate objects. For example%%timeit x = arr.copy() \n x *= 100
lets me time the*=
without timing thecopy
. – hpauljcelcius
through those different ways. Timing everything, doesn't let us do that. I won't mind seeing the timings of the pre-calculation part separately though. – Divakar