numpy - Fastest way to create an array in Python -
this question has answer here:
i want create 3d array in python, filled -1.
i tested these methods:
import numpy np l = 200 b = 100 h = 30 %timeit grid = [[[-1 x in range(l)] y in range(b)] z in range(h)] 1 loops, best of 3: 458 ms per loop %timeit grid = -1 * np.ones((l, b, h), dtype=np.int) 10 loops, best of 3: 35.5 ms per loop %timeit grid = np.zeros((l, b, h), dtype=np.int) - 1 10 loops, best of 3: 31.7 ms per loop %timeit grid = -1.0 * np.ones((l, b, h), dtype=np.float32) 10 loops, best of 3: 42.1 ms per loop %%timeit grid = np.empty((l,b,h)) grid.fill(-1.0) 100 loops, best of 3: 13.7 ms per loop so obviously, last 1 fastest. has faster method or @ least less memory intensive? because runs on raspberrypi.
the thing can think add of these methods faster dtype argument chosen take little memory possible.
assuming need no more space int8, method suggested @rutgerkassies in comments took long on system:
%timeit grid = np.full((l, b, h), -1, dtype=int8) 1000 loops, best of 3: 286 µs per loop for comparison, not specifying dtype (defaulting int32) took 10 times longer same method:
%timeit grid = np.full((l, b, h), -1) 100 loops, best of 3: 3.61 ms per loop your fastest method fast np.full (sometimes beating it):
%%timeit grid = np.empty((l,b,h)) grid.fill(-1) 100 loops, best of 3: 3.51 ms per loop or, dtype specified int8,
1000 loops, best of 3: 255 µs per loop edit: cheating, but, well...
%timeit grid = np.lib.stride_tricks.as_strided(np.array(-1, dtype=int8), (l, b, h), (0, 0, 0)) 100000 loops, best of 3: 12.4 per loop all that's happening here begin array of length one, np.array([-1]), , fiddle stride lengths grid looks array required dimensions.
if need actual array, can use grid = grid.copy(); makes creation of grid array fast quickest approaches suggested on elsewhere page.
Comments
Post a Comment