First iteration in for loop is slower

조회 수: 4 (최근 30일)
I Zendejas
I Zendejas 2014년 6월 27일
답변: ALVARO 2023년 2월 2일
I'm decoding some data which randomly can have sign, all I know is that there is a character before the point character and there are two characters after the point. I have noticed that the first iteration in the for loop is slower than the next iterations. I'm wondering whether you have any idea about it. Is that because a kind of initialization?
Here you go a part of my code:
close all; clear all; clc;
data='-0.01-0.020.03';
inc = [0 0 0];
inc_t = 0;
xyz_accel = [0 0 0];
for j=1:3
tic
if data(1+inc_t)=='-'
xyz_accel(1,j) = str2double( data(inc_t+1:inc_t+5) );
inc(1,j) = 5;
else
xyz_accel(1,j) = str2double( data(inc_t+1:inc_t+4) );
inc(1,j) = 4;
end
inc_t = sum(inc);
toc
end
xyz_accel
Elapsed time is 0.017351 seconds.
Elapsed time is 0.000255 seconds.
Elapsed time is 0.000327 seconds.
xyz_accel =
-0.0100 -0.0200 0.0300
Thanks in advanced.

채택된 답변

Ken Atwell
Ken Atwell 2014년 6월 27일
MATLAB works a bit harder up front to accelerate performance later. You're most likely seeing this effect.
The performance difference will tighten up if you remove the 'clear all'. The gap will not completely close, but the first iteration speeds up by 10-fold on my Mac.
  댓글 수: 2
I Zendejas
I Zendejas 2014년 6월 28일
OK Mr.Ken Atwell, it is good to know that. It is just that I searched similar questions and they have exactly the opposite case, they get iterations slower than the previous.
Thank you very much.
Image Analyst
Image Analyst 2014년 6월 28일
There can be reasons for that too, such as you're plotting or displaying an increasing number of things, or you're not preallocating memory and so you're dynamically reallocating larger and larger array sizes.

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

추가 답변 (1개)

ALVARO
ALVARO 2023년 2월 2일
I guess this comment only applies after 2015 version, but I believe what matlab is doing is jitting the for loop (Just in Time Compilation). It would be nice is someone could confirm this.

카테고리

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