简体   繁体   中英

Pure python faster than numpy on element-wise operation?

Can someone explain these results to me ? The pure Python seems to take less time than the numpy expression for element-wise exponentiation.

In [224]: ar=np.arange(1000)
          %timeit a**4
          100000 loops, best of 3: 5.22 µs per loop
In [225]: ar=range(1000)
          %timeit [ar[i]**4 for i in ar]
          1000 loops, best of 3: 205 µs per loop

Numpy total time= 100000*5.22 = 522000 µs

Pure Python total time = 1000*205 = 205000 µs

The pure Python version was timed for less iterations. That doesn't mean it was faster; that means timeit stopped running it so it wouldn't take 60 seconds* to get results. You can see from the per-loop time that the NumPy version was 40 times faster.

*200 microseconds per loop * 100,000 loops * 3 repetitions of the timing procedure

You're comparing the result of 1,000 runs against that of 100,000 runs. The numpy version ran 100,000 times and took 5.22 µs each time. The Python version only ran 1,000 times and took 205 µs per loop.

So while the overall timing might have greater, the individual per-operation time for numpy was ~40x less.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM