Ben*_*sen 3 matlab profiling runtime
我有一些代码需要很长时间才能运行(几个小时),我认为这是因为它在if语句中进行了大量的比较.我希望它运行得更快,有没有人有任何有用的建议来改善运行时?如果有人对减慢代码的速度有不同的看法,那么我可以尝试修复它,我们将不胜感激.
xPI = zeros(1,1783);
argList2 = zeros(1,1783);
aspList2 = zeros(1,1783);
cysList2 = zeros(1,1783);
gluList2 = zeros(1,1783);
hisList2 = zeros(1,1783);
lysList2 = zeros(1,1783);
tyrList2 = zeros(1,1783);
minList= xlsread('20110627.xls','CM19:CM25');
maxList= xlsread('20110627.xls','CN19:CN25');
N = length(pIList);
for i = 1:N
if (argList(i)>= minList(1) && argList(i) <= maxList(1)) ...
&& (aspList(i)>= minList(2) && aspList(i) <= maxList(2)) ...
&& (cysList(i)>= minList(3) && cysList(i) <= maxList(3)) ...
&& (gluList(i)>= minList(4) && gluList(i) <= maxList(4)) ...
&& (hisList(i)>= minList(5) && hisList(i) <= maxList(5)) ...
&& (lysList(i)>= minList(6) && lysList(i) <= maxList(6)) ...
&& (tyrList(i)>= minList(7) && tyrList(i) <= maxList(7))
xPI(i) = pIList(i);
argList2(i) = argList(i);
aspList2(i) = aspList(i);
cysList2(i) = cysList(i);
gluList2(i) = gluList(i);
hisList2(i) = hisList(i);
lysList2(i) = lysList(i);
tyrList2(i) = tyrList(i);
disp('passed test');
end
end
Run Code Online (Sandbox Code Playgroud)
你可以尝试矢量化代码; 我编写了一些示例数据集,并复制了您在下面执行的一些操作.
matA1 = floor(rand(10)*1000);
matB1 = floor(rand(10)*1000);
matA2 = zeros(10);
matB2 = zeros(10);
minList = [10, 20];
maxList = [100, 200];
indicesToCopy = ( matA1 >= minList(1) ) & ( matA1 <= maxList(1) ) & ( matB1 >= minList(2) ) & ( matB1 <= maxList(2) );
matA2(indicesToCopy) = matA1(indicesToCopy);
matB2(indicesToCopy) = matB1(indicesToCopy);
Run Code Online (Sandbox Code Playgroud)
不知道这是否更快,你必须尝试一下.
编辑:
这并不重要,因为你只打了两个电话,但xlsread
速度非常慢.您可以使用此函数的变体语法来加速这些调用.
num = xlsread(filename, sheet, 'range', 'basic')
Run Code Online (Sandbox Code Playgroud)
range
问题是忽略了参数并且读取了整个工作表,因此您将不得不正确地索引结果.
使用探查器查看哪些行或函数使用最多的执行时间.
通过矢量化代码,您可以大大提高执行速度.这意味着使用一次操作整个向量的操作,而不是使用for
-loop迭代它.就像是:
% make a logical vector indicating what you want to include
ii = (argList >= minList(1) & argList <= maxList(1)) & ...
% use it
argList2(ii) = arglist(ii); % copies over every element where the corresponding ii is 1
...
Run Code Online (Sandbox Code Playgroud)