Differences between Numpy divide and Python divide?

泪湿孤枕 提交于 2019-11-29 11:17:44

There doesn't appear to be any actual performance difference here.

When I run your code, and swap the two tests, whichever one comes second goes faster.

When I use timeit for proper benchmarking, they take about the same time (540ms for / vs. 539ms for divide).

My guess would be that the difference you measured was the time to malloc the array—the first one needs to do that, the second one can reuse the memory that just got freed.


But let's look at the source. The code in generate_umath.py creates the actual code, and it's assigning the same Ufunc (named numpy.core.umath.divide) to np.floor_divide and to the PyNumber_FloorDivide slot for np.ndarray. (If you're wondering why I looked up floor_divide when you're using divide and / instead of floor_divide and //, see the comment later where it deletes divide for Python 3 because it will be aliased it to true_divide.) IIRC, the actual code is a switch on types and sizes that ultimately ends up in one of the loop templates in loops.c.src.

So, beyond the differences in explicit Ufunc wrapper code vs. builtin method-wrapper wrapper code (which is going to be irrelevant for any array that isn't tiny), they end up in the same place.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!