Built-in functions VS explicit loops: which is faster in MATLAB?
6 次查看(过去 30 天)
显示 更早的评论
Hi all,
I did some speed tests with implicit functions and explicit loops, both repeat 1000 times and calculate average time. First one is eTe:
nh = 1000;
nw = 5;
nCount = 1000;
emtx = rand(nh, nw);
%%test ete
% implicit
tTime1 = 0;
for count = 1:nCount
tic;
ete = emtx' * emtx;
x = toc;
tTime1 = tTime1 + x;
end
aTime1 = tTime1 / nCount;
% explicit
etetest = zeros(nw, nw);
tTime2 = 0;
for count = 1:nCount
tic;
for i = 1:nw
for j = 1:nw
e1 = emtx(:, i);
e2 = emtx(:, j);
etetest(i, j) = etetest(i, j) + e1' * e2;
end
end
x = toc;
tTime2 = tTime2 + x;
end
aTime2 = tTime2 / nCount;
results are
aTime1 =
2.0515e-05
aTime2 =
1.9389e-04
second one tests cellfun:
nd = 100;
nt = 10;
ecell = mat2cell(emtx, nh, ones(1, nw));
% implicit
tTime3 = 0;
for count = 1:nCount
tic;
ecellres = cellfun(@(v) reshape(v, [nd, nt]), ecell, 'un', 0);
x = toc;
tTime3 = tTime3 + x;
end
aTime3 = tTime3 / nCount;
% explicit
ecellres1 = cell(1, nw);
tTime4 = 0;
for count = 1:nCount
tic;
for i = 1:nw
ecellres1(i) = {reshape(ecell{i}, [nd, nt])};
end
x = toc;
tTime4 = tTime4 + x;
end
aTime4 = tTime4 / nCount;
results are
aTime3 =
1.8522e-04
aTime4 =
2.5675e-05
In the first test, ete is faster than for loops; in the second test, for loops are faster than cellfun. As far as I understand, both ete and cellfun use loops in MATLAB, why is there a speed difference? Is there a critical point, where built-in functions are faster than loops?
Many thanks!
2 个评论
Adam
2017-5-17
cellfun is almost always slower than an equivalent for loop.
You should use
doc timeit
for timing function times though. tic/toc is not the most reliable, especially for such small run-times.
John D'Errico
2017-5-17
编辑:John D'Errico
2017-5-17
Which code will be faster very much depends on how you write the code. It depends on your coding skill. It depends on the specific problem. It often depends on problem size. Time required will often depend on machine dependent things, like your CPU, number of processors, amount of RAM. Finally, these questions often change over time, as TMW makes changes to their provided tools, changes in parser intelligence, etc.
So to answer which variation is faster is best done using simple calls to timeit, and the best measure is done by you on your machine, in the version of MATLAB that you will be using. The point is, you are asking a question that lacks a hard, fast, fixed answer, true on any computer, on any release of MATLAB.
tic and toc are terrible ways to test time. Use timeit instead!
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!