tic toc inside a timeit
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a function "test". Inside this test function, I have a for loop that goes from 1 to N. Since I want to know the average time for each iteration, I put tic /toc, and a variable called "Time_for" will give me the average time, as you can see in the code below
test(x)
tic
for i=1:N
some operations
% code
end
Time_for=toc/N % this result is displayed in the command window, and not saved as an output of the function
Now, I want to compute the time execution of the function. For this purpose, in the main of the program, I use the timeit function, as you can see below
f=@()test(x);
time_function=timeit(f);
My problem is that, when I run timeit, the variable "Time_for", that should just be displayed only once, it is actually displayed 10 times. And for each of these 10 times, the value slightly changes.
Why the toc function, inside a timeit, is computed multiple times?
Best,
Maria
0 个评论
采纳的回答
Adam
2014-10-27
I've never tried outputting to screen in a function wrapped in a timeit call, but I suspect the reason is simply because timeit runs your function multiple times in order to give a more accurate estimate of the function time than if you just ran it once with a tic toc. So if you output to the screen in your function it will likely do it however many times timeit runs your function.
Before timeit I used to create my own for loop, call my function many times and take an average, make sure each time had equal conditions and all that, but now timeit takes care of that for you.
0 个评论
更多回答(1 个)
Sean de Wolski
2014-10-27
This is actually mentioned in the tips at the bottom of the doc for timeit
Unexpected results occur when you call tic and toc inside of timeit. If you are going to do this, be sure to assign an output to tic
myt = tic;
mystuff
toc(myt)
Of course printing to the command line takes some time too, so I would also disable that if really trying to time the code.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!