I performed some timings of the solutions presented by @AustinHastings in his answer on my machine at work (Linux 64bit, Intel Core i7-2600, 16GB RAM, Anaconda Python 3,
).
The timing function was slightly modified to use repetitions get more accurate results as well as to easier get the timings for visual display.
def time_func(f, shape=1000, n_reps=10):
global COMBINED_SHAPE
COMBINED_SHAPE = shape
start_time = timeit.default_timer()
for _ in range(n_reps):
ca = f()
assert np.shape(ca)[0] == COMBINED_SHAPE
average_time = (timeit.default_timer() - start_time) / n_reps
print(f"Time for {f.__name__}: "
f"{average_time * 1000:.6f} ms")
return average_time
# the functions go here
def perform_benchmark(*shapes):
results = np.zeros((len(shapes), 5))
for i, shape in enumerate(shapes):
print(f"shape: {shape}")
print(f"array size: {shape * 8 / 1024**3:.3f} GB")
results[i, 0] = time_func(orig, shape=shape)
results[i, 1] = time_func(concat, shape=shape)
results[i, 2] = time_func(block, shape=shape)
results[i, 3] = time_func(stack_ravel, shape=shape)
results[i, 4] = time_func(stack_flatten, shape=shape)
plt.figure()
plt.plot(shapes, results, marker="o")
plt.xlim((shapes[0], shapes[-1]))
plt.grid(ls="--")
plt.legend(["orig", "concat", "block", "stack_ravel", "stack_flatten"])
plt.figure()
plt.loglog(shapes, results, marker="o")
plt.xlim((shapes[0], shapes[-1]))
plt.grid(ls="--")
plt.legend(["orig", "concat", "block", "stack_ravel", "stack_flatten"])
plt.show()
if __name__ == '__main__':
perform_benchmark(
100000, 300000, 500000,
1000000, 3000000, 5000000,
10000000, 30000000, 50000000,
100000000, 300000000
)
The array size of \$500 \times 10^6\$ elements which would have come next was to big to fit in RAM and lead to excessive swapping (your original would be at \$ 900 \times 10^6 \$).
When looking at the linear plot you will see no difference between the solutions on all but stack_flatten
which consistently takes about twice the time of the other solutions.
In an loglog graph you can see this as an approximately constant offset between stack_flatten
and the other solutions.
These findings seem to be consistent with what Austin Hastings presented in his answer.