反转 numpy 数组的最有效方法 [英] Most efficient way to reverse a numpy array
问题描述
信不信由你,在分析了我当前的代码之后,numpy 数组反转的重复操作占用了大量的运行时间.我现在拥有的是常见的基于视图的方法:
Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method:
reversed_arr = arr[::-1]
有没有其他方法可以更有效地做到这一点,或者这只是我对不切实际的 numpy 性能的痴迷所造成的错觉?
Is there any other way to do it more efficiently, or is it just an illusion from my obsession with unrealistic numpy performance?
推荐答案
当您创建 reversed_arr
时,您正在创建原始数组的视图.然后您可以更改原始数组,视图将更新以反映更改.
When you create reversed_arr
you are creating a view into the original array. You can then change the original array, and the view will update to reflect the changes.
您是否比需要的更频繁地重新创建视图?你应该能够做这样的事情:
Are you re-creating the view more often than you need to? You should be able to do something like this:
arr = np.array(some_sequence)
reversed_arr = arr[::-1]
do_something(arr)
look_at(reversed_arr)
do_something_else(arr)
look_at(reversed_arr)
我不是 numpy 专家,但这似乎是在 numpy 中做事的最快方法.如果这是你已经在做的事情,我认为你无法改进它.
I'm not a numpy expert, but this seems like it would be the fastest way to do things in numpy. If this is what you are already doing, I don't think you can improve on it.
附言在这里对 numpy 视图进行了很好的讨论:
P.S. Great discussion of numpy views here:
这篇关于反转 numpy 数组的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!