Most efficient way to reverse a numpy array

后端 未结 7 673
南旧
南旧 2020-11-30 16:43

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 com

相关标签:
7条回答
  • 2020-11-30 17:47

    As mentioned above, a[::-1] really only creates a view, so it's a constant-time operation (and as such doesn't take longer as the array grows). If you need the array to be contiguous (for example because you're performing many vector operations with it), ascontiguousarray is about as fast as flipud/fliplr:


    Code to generate the plot:

    import numpy
    import perfplot
    
    
    perfplot.show(
        setup=lambda n: numpy.random.randint(0, 1000, n),
        kernels=[
            lambda a: a[::-1],
            lambda a: numpy.ascontiguousarray(a[::-1]),
            lambda a: numpy.fliplr([a])[0],
        ],
        labels=["a[::-1]", "ascontiguousarray(a[::-1])", "fliplr"],
        n_range=[2 ** k for k in range(25)],
        xlabel="len(a)",
    )
    
    0 讨论(0)
提交回复
热议问题