python - Shouldn't preallocation of arrays in numpy be faster? -


i confused why test2 not faster test1 in following code:

import timeit  setup = """ import numpy np = np.ones((220, 220, 220)) b = np.ones((220, 220, 220))  class store:     def __init__(self):         self.c = np.empty((220, 220, 220)) z = store() """  test1 = """ c = + b """  test2 = """ z.c = + b """  print timeit.timeit(test1, setup, number=1000) print timeit.timeit(test2, setup, number=1000) 

which gave me: 40.9241290092 40.7675480843

i thought because z.c preallocated memory, there less overhead every time added a+b , needed place store it, i.e. less calls malloc behind scenes or that. missing?

allocation fast operation, addition more expensive :

in [7]: %timeit  np.empty((220, 220, 220)) 1000 loops, best of 3: 472 µs per loop  in [8]: u= np.ones((220, 220, 220))  in [9]: %timeit  u+u 10 loops, best of 3: 73.5 ms per loop  

so, correctly update array (z.c[:]= a+b) not win lot in case.( ~ 0.5 % )


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -