Differences in transpose functions in python

I am creating a large matrix (100x100, let it be called X) with random numbers, with numpy.matrix (), so I have numpy.ndarray.

I was wondering if there is a difference between the two operations:

  • numpy.transpose (X)
  • XT

I measured the time of each operation in a loop with a range of 1000 and it seems that XT is significantly faster than numpy.transpose (X)

Benchmarks added:

For a 100x100 matrix, I got the following results with XT and numpy.tranpose (X)

In the range 10,000 loop:

  • 7421 / 10.000: XT fast
  • 1256 / 10.000: numpy.transpose (X) is faster
  • 1323 / 10.000: The same time or calculation difference is too small to determine

Added code below

import numpy as np import time np_transpose_count = 0 T_transpose_count = 0 equal_count = 0 for i in range(10000): Se = np.random.rand(100,100) tic1 =time.clock() ST_T = Se.T toc1=time.clock() tic2 =time.clock() ST_np = np.transpose(Se) toc2=time.clock() if (toc1-tic1) < (toc2-tic2): T_transpose_count+=1 elif (toc1-tic1) > (toc2-tic2): np_transpose_count+=1 else: equal_count+=1 print(T_transpose_count, np_transpose_count, equal_count) 

Respectfully Hum

+7
python numpy transpose
source share
1 answer

Using Ipython %timeit magic, I get:

 In [218]: X=np.ones((100,100)) In [219]: timeit XT 1000000 loops, best of 3: 379 ns per loop In [220]: timeit X.transpose() 1000000 loops, best of 3: 470 ns per loop In [221]: timeit np.transpose(X) 1000000 loops, best of 3: 993 ns per loop In [222]: timeit X+1 10000 loops, best of 3: 21.6 ยตs per loop 

So yes, .T is faster and the function is slower. But compare these times with time for a simple addition

Or a copy or fragment

 In [223]: timeit X.copy() 100000 loops, best of 3: 10.8 ยตs per loop In [224]: timeit X[:] 1000000 loops, best of 3: 465 ns per loop 

Transposing in all its forms returns a new array object with new shape and strides , but with a common data buffer (look at the dictionary .__array_interface__ to see this). Therefore, it takes about the same time as other actions that return a view . But none of the transpose functions copy data or iterate through it. So the time difference is just the result of a call over your head.

Again with ipython magic

 np.transpose?? def transpose(a, axes=None): try: transpose = a.transpose except AttributeError: return _wrapit(a, 'transpose', axes) return transpose(axes) 

So np.function(X) ends with a call to X.transpose() .

I need to look at the numpy code, but I remember that .T implemented as attribute (not quite the same as property ). I suspect this is faster because it does not use the axes parameter and thus saves a function call of C or two.

+5
source share

All Articles