【发布时间】:2011-07-07 11:32:03
【问题描述】:
在循环的每次迭代中,我都在计算一个 MATLAB 矩阵。这些矩阵都必须连接在一起以创建一个最终矩阵。我在进入循环之前知道这个最终矩阵的维度,所以我虽然使用“零”函数预分配矩阵比初始化一个空数组然后简单地在循环的每次迭代中附加子数组要快。奇怪的是,当我预分配时,我的程序运行速度要慢得多。这是代码(只有第一行和最后一行不同):
这很慢:
w_cuda = zeros(w_rows, w_cols, f_cols);
for j=0:num_groups-1
% gets # of rows & cols in W. The last group is a special
% case because it may have fewer than max_row_size rows
if (j == num_groups-1 && mod(w_rows, max_row_size) ~= 0)
num_rows_sub = w_rows - (max_row_size * j);
else
num_rows_sub = max_row_size;
end;
% calculate correct W and f matrices
start_index = (max_row_size * j) + 1;
end_index = start_index + num_rows_sub - 1;
w_sub = W(start_index:end_index,:);
f_sub = filterBank(start_index:end_index,:);
% Obtain sub-matrix
w_cuda_sub = nopack_cu(w_sub,f_sub);
% Incorporate sub-matrix into final matrix
w_cuda(start_index:end_index,:,:) = w_cuda_sub;
end
这很快:
w_cuda = [];
for j=0:num_groups-1
% gets # of rows & cols in W. The last group is a special
% case because it may have fewer than max_row_size rows
if (j == num_groups-1 && mod(w_rows, max_row_size) ~= 0)
num_rows_sub = w_rows - (max_row_size * j);
else
num_rows_sub = max_row_size;
end;
% calculate correct W and f matrices
start_index = (max_row_size * j) + 1;
end_index = start_index + num_rows_sub - 1;
w_sub = W(start_index:end_index,:);
f_sub = filterBank(start_index:end_index,:);
% Obtain sub-matrix
w_cuda_sub = nopack_cu(w_sub,f_sub);
% Incorporate sub-matrix into final matrix
w_cuda = [w_cuda; w_cuda_sub];
end
就其他可能有用的信息而言——我的矩阵是 3D 的,其中的数字很复杂。与往常一样,我们感谢您的任何见解。
【问题讨论】:
-
您的部分代码似乎丢失了。未定义矩阵或函数“W”和“filterBank”。
-
是的,这只是我认为相关的代码部分。谢谢。
-
不知道你的代码在做什么,或者至少与你的代码在做什么有一些可执行的类比,谁能告诉你为什么它很慢?从您的代码中甚至不清楚 W、filterBank 和 nopack_cu 是矩阵还是函数。看起来 w_rows、w_cols、f_cols、num_groups、max_row_size 以某种方式相互关联,但尚不清楚。如果您可以提供一个可执行示例,我可以进一步查看它。我怀疑在我的机器上,上面的例子会比下面的例子执行得更快。
-
查看变量名称 - 您使用的是 CUDA 还是其他并行扩展?
-
是的,Xodarap;我正在使用 MEX 进行 CUDA 调用,随后将结果返回给 w_cuda_sub。这一步的时间在我提供的两个代码示例之间是相同的。
标签: arrays memory matlab performance memory-management