我一直听说在MATLAB中,向量化的代码比for循环运行速度更快。然而,当我尝试将我的MATLAB代码向量化时,它似乎运行得更慢了。
我使用了
此外,在我的主程序中,我使用了一个很大的N值,即
为什么向量化的速度如此之慢,我该如何进一步提高速度?
“向量化”版本
“for循环”版本
我使用了
tic
和toc
来测量时间。我只改变了程序中一个函数的实现方式。我的向量化版本运行了47.228801
秒,而我的for循环版本运行了16.962089
秒。此外,在我的主程序中,我使用了一个很大的N值,即
N = 1000000
,数据集大小为1 301
,我对每个版本都进行了多次运行,使用相同大小和N的不同数据集。为什么向量化的速度如此之慢,我该如何进一步提高速度?
“向量化”版本
function [RNGSet] = RNGAnal(N,DataSet)
%Creates a random number generated set of numbers to check accuracy overall
% This function will produce random numbers and normalize a new Data set
% that is derived from an old data set by multiply random numbers and
% then dividing by N/2
randData = randint(N,length(DataSet));
tempData = repmat(DataSet,N,1);
RNGSet = randData .* tempData;
RNGSet = sum(RNGSet,1) / (N/2); % sum and normalize by the N
end
“for循环”版本
function [RNGData] = RNGAnsys(N,Data)
%RNGAnsys This function produces statistical RNG data using a for loop
% This function will produce RNGData that will be used to plot on another
% plot that possesses the actual data
multData = zeros(N,length(Data));
for i = 1:length(Data)
photAbs = randint(N,1); % Create N number of random 0's or 1's
multData(:,i) = Data(i) * photAbs; % multiply each element in the molar data by the random numbers
end
sumData = sum(multData,1); % sum each individual energy level's data point
RNGData = (sumData/(N/2))'; % divide by n, but account for 0.5 average by n/2
end
bsxfun
)来避免使用repmat
? - Ben Voigtrepmat
通常比bsxfun
慢:尝试使用bsxfun(@times, randData, DataSet)
。此外,在旧版本的Matlab中,循环比向量化更慢,但使用JIT编译器和预分配的循环可以相当有效。 - Dan