Recently I came across someone using
from timeit import timeit
import numpy as np
array1015 = np.random.rand(10,15)
First, the operations are so fast it doesn't really matter if one optimizes there!
%timeit nptrans() # 100000 loops, best of 3: 2.11 µs per loop %timeit npt() # 1000000 loops, best of 3: 905 ns per loop
Optimizing this doesn't make sense except you would be doing millions of transposes and nothing else. Even adding them is much, much slower:
%timeit array1015 + array1015 # 100000 loops, best of 3: 3.55 µs per loop
and addition should be really, really fast!
However there is some overhead in
np.transpose that isn't present in
np.transposein the end calls the objects
.transpose-method which means it has to look-up the method of the object and call it.
So the overhead you see is the result of 2 function calls and a
np.transpose function is actually python so you can see the overhead quite easily (I removed comments):
def transpose(a, axes=None): return _wrapfunc(a, 'transpose', axes) # extra function call def _wrapfunc(obj, method, *args, **kwds): try: return getattr(obj, method)(*args, **kwds) # here it finally calls ndarray.transpose() except (AttributeError, TypeError): return _wrapit(obj, method, *args, **kwds)