import numpy as np from time import process_time as T N=10000 a = np.random.rand(N,N,3) # values are stored a[0,0,0] a[0,0,1] a[0,0,2] ... a[0,0,N] a[0,1,0] a[0,1,1] ... tic = T() a[:,:,0] = a[:,:,1] # values are far in memory, collecting them is slow a[:,:,2] = a[:,:,0] a[:,:,1] = a[:,:,2] # ahem, this is *not* a swapping operation toc = T() - tic print(toc,"seconds using (N,N,3) in default row major order") # change index order to fortran's column major order # values are stored a[0,0,0] a[1,0,0] a[2,0,0] ... a[N,0,0] a[0,1,0] a[1,1,0] ... a = np.random.rand(N,N,3) tic = T() a = np.asfortranarray(a) # this takes time a[:,:,0] = a[:,:,1] # values are consequtive in memory, collecting them is fast a[:,:,2] = a[:,:,0] a[:,:,1] = a[:,:,2] toc = T() - tic print(toc,"seconds using (N,N,3) in column major order") # same size task, but define the array in different order to begin with a = np.random.rand(3,N,N) tic = T() a[0,:,:] = a[1,:,:] # values are consequtive in memory, collecting them is fast a[2,:,:] = a[0,:,:] a[1,:,:] = a[2,:,:] toc = T() - tic print(toc,"seconds using (3,N,N) in default row major order") #0.9668405870000001 seconds using (N,N,3) in default row major order #0.9624588530000002 seconds using (N,N,3) in column major order #0.12479739399999978 seconds using (3,N,N) in default row major order