Can someone explain this large difference in compute time?
显示 更早的评论
The two computations below should be identical, but tic/toc reports very different compute times for them in R2018a. Why?
function test
N=3e4+1;
F1=tril( triu(ones(N),0), 0);
F2=diag(ones(N,1));
x=rand(1e4,1); x(N)=0;
tic;
z1=x.'*(F1*x)+7;
toc;
%Elapsed time is 0.231846 seconds.
tic;
z2=x.'*(F2*x)+7;
toc;
%Elapsed time is 2.148849 seconds.
end
11 个评论
OCDER
2018-10-23
That's very interesting. If you copy F2 as another variable, F3, you get the same speed boost as F1.
N = 10000;
x = rand(N,1);
x(end) = 0;
F1 = tril(triu(ones(N),0), 0);
F2 = diag(ones(N,1),0);
F3 = F2;
tic
z1 = x.'*(F1*x)+7;
toc %Elapsed time is 0.049871 seconds.
tic
z2 = x.'*(F2*x)+7;
toc %Elapsed time is 0.138747 seconds.
tic
z3 = x.'*(F3*x)+7;
toc %Elapsed time is 0.043385 seconds.
if isequal(F1, F2); disp('F1 = F2, Checked'); end
if isequal(F2, F3); disp('F2 = F3, Checked'); end
if isequal(z1, z2); disp('z1 = z2, Checked'); end
if isequal(z2, z3); disp('z2 = z3, Checked'); end
Bruno Luong
2018-10-23
编辑:Bruno Luong
2018-10-23
Prepare for this:
N = 10000;
x = rand(N,1);
x(end) = 0;
F1 = tril(triu(ones(N),0), 0);
F2 = diag(ones(N,1),0);
F3 = F2;
tic
z3 = x.'*(F3*x)+7;
toc %Elapsed time is 0.216113 seconds.
tic
z1 = x.'*(F1*x)+7;
toc %Elapsed time is 0.021705 seconds.
tic
z2 = x.'*(F2*x)+7;
toc %Elapsed time is 0.021853 seconds.
Bruno Luong
2018-10-23
编辑:Bruno Luong
2018-10-23
I read in a BLOG written by someone on TMW that discuss about of storing the results of a function call and returning the same results without computing again if the function is invoked with the same input arguments.
Can it explains that?
Matt J
2018-10-23
Matt J
2018-10-23
Bruno Luong
2018-10-23
编辑:Bruno Luong
2018-10-23
"You mean memoize()?"
Matt J
2018-10-23
Bruno Luong
2018-10-23
Because the first call with F2/F3 takes more time regardless which one. They shares mxArray header.
Matt J
2018-10-23
Bruno Luong
2018-10-23
But I my comment is not applicable your OP, I comment on OCER and mine finding.
OCDER
2018-10-23
Interesting finding and perhaps another hint. Just accessing F2 via a function like round, floor, ceil fixes the issue again.
N = 10000;
x = rand(N,1);
x(end) = 0;
F1 = tril(triu(ones(N),0), 0);
F2 = diag(ones(N,1),0);
F3 = round(F2); %<=== doing this round here affects F2 too, somehow...
tic
z1 = x.'*(F1*x)+7;
toc %Elapsed time is 0.048131 seconds.
tic
z2 = x.'*(F2*x)+7;
toc %Elapsed time is 0.050953 seconds. <=== time is faster
tic
z3 = x.'*(F3*x)+7;
toc %Elapsed time is 0.045269 seconds.
采纳的回答
更多回答(1 个)
Bruno Luong
2018-10-23
编辑:Bruno Luong
2018-10-23
0 个投票
Interesting. Just a guess: TRIU and TRIL mark internally the resulting mxArray and MATLAB detects later the specific form and call specific faster BLAS routine when MTIMES is invokes.
类别
在 帮助中心 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!