Tic toc command giving erroneous result
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/163782/image.png)
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)');
0 comentarios
Respuestas (1)
David Sanchez
el 4 de Jun. de 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.
0 comentarios
Ver también
Categorías
Más información sobre Language Fundamentals en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!