Frequency and use of random transpose functions

So why does NumPy transpose .Tfaster than np.transpose()?

b = np.arange(10)

#Transpose .T
t=b.reshape(2,5).T

#Transpose function
t = np.transpose(b.reshape(2,5))

#Transpose function without wrapper
t = b.reshape(2,5).transpose()

I did timeitas in Jupyter:

%timeit -n 1000 b.reshape(2,5).T

1000 loops, best of 3: 391 ns per loop

%timeit -n 1000 np.transpose(b.reshape(2,5))

1000 loops, best of 3: 600 ns per loop

%timeit -n 1000 b.reshape(2,5).transpose()

1000 loops, best of 3: 422 ns per loop

and to check scalability I made a big matrix:

b = np.arange( 100000000)

%timeit -n 1000 b.reshape(10000,10000).T

1000 loops, best of 3: 390 ns per loop

%timeit -n 1000 np.transpose(b.reshape(10000,10000))

1000 loops, best of 3: 611 ns per loop

%timeit -n 1000 b.reshape(10000,10000).transpose()

1000 loops, best of 3: 435 ns per loop

In both cases, the method is .Tabout 2 times faster than the wrapper, and a bit faster than using .transpose(), why is this? Is there a use case where np.transposeit would be better?

-1
source share
1 answer

One reason may be that it np.transpose(a)simply calls a.transpose()internally, but a.transpose()is more direct. In the source you have:

def transpose(a, axes=None):
    return _wrapfunc(a, 'transpose', axes)

Where _wrapfuncin turn is simple :

def _wrapfunc(obj, method, *args, **kwds):
    try:
        return getattr(obj, method)(*args, **kwds)
    except (AttributeError, TypeError):
        return _wrapit(obj, method, *args, **kwds)

getattr(a, 'transpose'). _wrapfunc , ndarray , .

(: .T .transpose(), , , < 2 .)

+2

Source: https://habr.com/ru/post/1694623/


All Articles