stackは遅い
ndarrayをlistに貯めてconcatするほうが、毎回stackしていくより速い GPT-4.icon
code:py
import numpy as np
import time
# Initialize variables
shape = (100, 100)
n_iterations = 1000
# Using Python list and then convert it to ndarray
list_method_start_time = time.time()
list_of_arrays = []
for _ in range(n_iterations):
array = np.random.rand(*shape)
list_of_arrays.append(array)
concatenated_array = np.concatenate(list_of_arrays, axis=0)
list_method_end_time = time.time()
list_method_time = list_method_end_time - list_method_start_time
# Using numpy stack
stack_method_start_time = time.time()
stack_of_arrays = np.empty((0, shape1)) for _ in range(n_iterations):
array = np.random.rand(*shape)
stack_of_arrays = np.vstack((stack_of_arrays, array))
stack_method_end_time = time.time()
stack_method_time = stack_method_end_time - stack_method_start_time
list_method_time, stack_method_time
code:result
(0.42954111099243164, 56.57924294471741)