该算法一次又一次地重复相同的事情.我希望在每次试验中得到相同的时间,但我在四次相同的试验中得到了非常意想不到的时间
我预计曲线是相同的,但它们的行为完全不同.原因可能在于tic/toc精度.
我应该在Matlab中使用什么样的分析/计时工具?
我在下面的代码中做错了什么?tic/toc剖析的可靠性如何?
无论如何要保证一致的结果?
算法
A=[]; for ii=1:25 tic; timerval=tic; AlgoCalculatesTheSameThing(); tElapsed=toc(timerval); A=[A,tElapsed]; end
Stewie Griff.. 7
你应该试试timeit
.
看看这个相关的问题:
如何对Matlab进程进行基准测试?
Sam Roberts的片段回答了另一个问题:
它处理许多与为您标记MATLAB代码相关的微妙问题,例如:
通过将基准代码包装在函数中来确保使用JIT编译
预热代码
多次运行代码并进行平均
看看这个问题,讨论热身问题:
为什么在脚本"预热"后Matlab运行得更快?
更新:自从timeit
首次在fileexchange提交以来,源代码在这里可用,可以进行研究和分析(与大多数其他MATLAB函数相反).从标题timeit.m
:
% TIMEIT handles automatically the usual benchmarking procedures of "warming
% up" F, figuring out how many times to repeat F in a timing loop, etc.
% TIMEIT also compensates for the estimated time-measurement overhead
% associated with tic/toc and with calling function handles. TIMEIT returns
% the median of several repeated measurements.
您可以一步一步地完成该功能.我认为这些评论非常好并具有描述性.当然,Mathworks可能已经改变了部分代码,但整体功能都存在.
例如,要考虑运行所需的时间tic/toc
:
function t = tictocTimeExperiment
% Call tic/toc 100 times and return the average time required.
它后来从总时间中减去.
关于计算次数,说如下:
function t = roughEstimate(f, num_f_outputs)
% Return rough estimate of time required for one execution of
% f(). Basic warmups are done, but no fancy looping, medians,
% etc.
此粗略估计用于确定计算应运行的次数.
如果要更改计算次数,可以自行修改该timeit
功能,因为它可用.我建议您将其保存为my_timeit
其他内容,以免您覆盖内置版本.