Tic toc command giving erroneous result

1 view (last 30 days)
Aditi
Aditi on 4 Jun 2014
Answered: David Sanchez on 4 Jun 2014
Here is my code
axis([0 5 -30 30]);
c=0;
theta=pi/6;
dt=1e-5;
nstep=round(5/dt);
stheta=0;
x1=theta;
x2=stheta;
dx1=x2;
dx2=-c*x2-21.791*sin(x1);
X=zeros(2,nstep);
V=zeros(2,nstep);
t=0:dt:(nstep-1)*dt;
tic
X(:,1)=[x1;x2];
V(:,1)=[dx1;dx2];
for i=2:(nstep)
X(:,i)=(dt*(V(:,i-1)))+X(:,i-1);
V(:,i)=[X(2,i);-c*X(2,i)-21.791*X(1,i)];
end
toc
plot(t,(180/pi)*X(1,:))
figure
plot(t,X(2,:))
In the above case I am using tic before X(:,1)=[x1;x2] and in the code below I am using tic before the for loop.
axis([0 5 -30 30]);
c=0;
theta=pi/6;
dt=1e-5;
nstep=round(5/dt);
stheta=0;
x1=theta;
x2=stheta;
dx1=x2;
dx2=-c*x2-21.791*sin(x1);
X=zeros(2,nstep);
V=zeros(2,nstep);
t=0:dt:(nstep-1)*dt;
X(:,1)=[x1;x2];
V(:,1)=[dx1;dx2];
tic
for i=2:(nstep)
X(:,i)=(dt*(V(:,i-1)))+X(:,i-1);
V(:,i)=[X(2,i);-c*X(2,i)-21.791*X(1,i)];
end
toc
plot(t,(180/pi)*X(1,:))
figure
plot(t,X(2,:))
But the time required in 1st case is less than that required in the second case and is varying. Why is it so I have plotted the histogram for both the case.
The code for histogram is
axis([0 5 -30 30]);
c=0;
theta=pi/6;
dt=1e-5;
nstep=round(5/dt);
stheta=0;
x1=theta;
x2=stheta;
dx1=x2;
dx2=-c*x2-21.791*sin(x1);
X=zeros(2,nstep);
V=zeros(2,nstep);
t=0:dt:(nstep-1)*dt;
comp_time = [];
for j=1:50
tic
X(:,1)=[x1;x2];
V(:,1)=[dx1;dx2];
for i=2:(nstep)
X(:,i)=(dt*(V(:,i-1)))+X(:,i-1);
V(:,i)=[X(2,i);-c*X(2,i)-21.791*X(1,i)];
end
comp_time = [comp_time,toc];
end
hist(comp_time);
title('Before X(:,1)=[x1;x2]');
comp_time = [];
for j=1:50
X(:,1)=[x1;x2];
V(:,1)=[dx1;dx2];
tic
for i=2:(nstep)
X(:,i)=(dt*(V(:,i-1)))+X(:,i-1);
V(:,i)=[X(2,i);-c*X(2,i)-21.791*X(1,i)];
end
comp_time = [comp_time,toc];
end
figure;
hist(comp_time);
title('Before for i=2:(nstep)');

Answers (1)

David Sanchez
David Sanchez on 4 Jun 2014
The time taken to run both scripts are insignificantly different. There are only two lines of code of difference between them:
X(:,1)=[x1;x2];
V(:,1)=[dx1;dx2];
Your system will fly through this two lines and will make almost no distinction between both scripts. Depending on the processes running in your system during the processing of the scripts ( most of them hidden processes ), the time taken will change.
You say
"But the time required in 1st case is less than that required in the second case and is varying."
You should be aware that it is faster sometimes ( I took the time to run it too several times ), and some others it is a bit slower. Your histogram shows it too.

Categories

Find more on Language Fundamentals in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!