timeit() for a block of code/precise time measurement for a block of code

조회 수: 4 (최근 30일)
Ilya
Ilya 2015년 6월 9일
편집: Ilya 2015년 6월 9일
I have a code in which certain blocks are 'auxiliary' and others need to be measured for their running time. So it looks like:
function [out1, .., outN, time] = xyz(arg1, .., argN)
[code 1]; % auxiliary
[code 2]; % time needs to be measured
[code 3]; % auxiliary
[code 4]; % time needs to be measured
Btw, auxiliary means that this code is 'implementation specific' and doesn't constitute the main part of the algorithm.
I'd like to provide robust time estimates, which is possible with timeit(), but then anonymous functions need to be defined for every piece of code (afaik). This is not always easy to do...
Is there any known way to make timeit() work as tic .. toc, i.e. to make it measure the running time of arbitrary code pieces like e.g.:
L = Min;
for i = 1:m
L(i,i) = max(L(i,:));
end
Here it's unclear how to incorporate a loop into an anonymous function. Sometimes loops can be avoided, but sometimes not. Some other examples are probably possible.
Should I use tic .. toc in such situations?

채택된 답변

Guillaume
Guillaume 2015년 6월 9일
Because timeit calls the code under evaluation multiple times to reduce uncertainty due to jitter, etc., it needs to be in its own function.
Your code appear to be a very good candidate for refactoring anyway, since the function is clearly divided into four separate components. It would make sense to have each of these components as individual function.
otherwise, yes, you have to use tic and toc.
  댓글 수: 1
Ilya
Ilya 2015년 6월 9일
편집: Ilya 2015년 6월 9일
Thanks for the explanation, I even could realize it myself.. The function is divided in more than 4 fragments and it's a bit more complicated, what is shown is just a simplified example. E.g. sometimes I compute optional output which is not for the main purpose of the algorithm but for its performance estimation. But I'll consider refactoring.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by