Какой самый быстрый способ объединить список массивов-пустышек в один массив, если знать длину списка и размер массивов, который одинаков для всех?
Я попробовал два подхода:
A вы можете видеть, что vstack
быстрее, но по какой-то причине первый запуск занимает в три раза больше времени, чем второй. Я предполагаю, что это вызвано (отсутствует) preallocation . Так как бы я выделил массив для vstack
? Или ты знаешь более быстрый метод?
Спасибо!
[UPDATE]
Я хочу (25280, 320)
не (80, 320, 320)
, что означает, merged_array = array(list_of_arrays)
не будет работать для меня. Спасибо Joris за то, что указал на это !!!
Выход:
0.547468900681 s merged_array = array(first_list_of_arrays)
0.547191858292 s merged_array = array(second_list_of_arrays)
0.656183958054 s vstack first
0.236850976944 s vstack second
Код:
import numpy
import time
width = 320
height = 320
n_matrices=80
secondmatrices = list()
for i in range(n_matrices):
temp = numpy.random.rand(height, width).astype(numpy.float32)
secondmatrices.append(numpy.round(temp*9))
firstmatrices = list()
for i in range(n_matrices):
temp = numpy.random.rand(height, width).astype(numpy.float32)
firstmatrices.append(numpy.round(temp*9))
t1 = time.time()
first1=numpy.array(firstmatrices)
print time.time() - t1, "s merged_array = array(first_list_of_arrays)"
t1 = time.time()
second1=numpy.array(secondmatrices)
print time.time() - t1, "s merged_array = array(second_list_of_arrays)"
t1 = time.time()
first2 = firstmatrices.pop()
for i in range(len(firstmatrices)):
first2 = numpy.vstack((firstmatrices.pop(),first2))
print time.time() - t1, "s vstack first"
t1 = time.time()
second2 = secondmatrices.pop()
for i in range(len(secondmatrices)):
second2 = numpy.vstack((secondmatrices.pop(),second2))
print time.time() - t1, "s vstack second"