Timing multiple Matlab functions
이전 댓글 표시
Hi!
I have two different ways of calculating a factorial of any number, for this program its 150!. I want to time the two functions and compare how much time they require in a plot.
This is my code so far:
clear all, close all, clc
n=150;
t1=zeros(1,n);
t2=zeros(1,n);
A=zeros(1,n);
B=ones(1,n);
f=1;
tic;
for i=1:n
f=f*i;
A(1,i)=f;
t1(i)=toc;
end;
tic;
for i=2:n
B(i)=B(i-1)*i;
t2(i)=toc;
end;
plot(t1,A,t2,B)
I do get a plot with the correct graphs, however I am concerned that the times are not correct since first of all, the first for-loop is faster than the second one and I think it should be around. Also, I have tried changing their places in the program and I get different results when I do.
How can I change this to get Matlab to time these functions accurately? Also, if you have a suggestion I would be very thankful if you could also point out what I am doing wrong.
Thank you!
채택된 답변
추가 답변 (1개)
Titus Edelhofer
2016년 2월 17일
Hi,
here is some code how you can test:
function testfactorial
n = 150;
t1 = timeit(@() fact1(n), 1)
t2 = timeit(@() fact2(n), 1)
function A = fact1(n)
f = 1;
A = zeros(1, n);
for i=1:n
f=f*i;
A(1,i)=f;
end
function B = fact2(n)
B = zeros(1, n);
for i=2:n
B(i)=B(i-1)*i;
end
If you run this a couple of times you will see one time t1 smaller, the other t2. So they are equally good and differences are stochastical ...
Titus
댓글 수: 1
Alexander Engman
2016년 2월 17일
편집: Alexander Engman
2016년 2월 17일
카테고리
도움말 센터 및 File Exchange에서 Variables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!