timings.m

来自「matlab宝典,电子工业出版社,包含该书的源码12-14章」· M 代码 · 共 62 行

M
62
字号
function timings
% Script file timings.m
%
% Purpose:
%   This program calculates the time reguired to 
%  calculate the squares of all integers from 1 to
%  10,000 in three different ways:
%  1.Using a for loop with an uninitialized output array
%  2.Using a for loop with a pre-allocated output array
%  3.Using vectors.

% Define variables:
% ii,jj    Loop index
% ave1     average time for method 1
% ave2     average time for method 2
% ave3     average time for method 3
% maxcount number of times to loop calculation
% square   array of squares

%Using a for loop with an uninitialized output array
maxcount=1;
tic;
for jj=1:maxcount
clear square
for ii=1:10000
    square(ii)=ii^2;
end
end
ave1=(toc)/maxcount;

%Using a for loop with a pre-allocated output array
maxcount=50;
tic;
for jj=1:maxcount
clear square
square=zeros(1,10000);
for ii=1:10000
    square(ii)=ii^2;
end
end
ave2=(toc)/maxcount;

%Using vectors
maxcount=100;
tic;
for jj=1:maxcount
clear square
ii=1:10000;
    square=ii.^2;
end
ave3=(toc)/maxcount;

%display the results
fprintf('Loop/uninitialized array= %9.5f\n',ave1);
fprintf('Loop/initialized array= %9.5f\n',ave2);
fprintf('vectorized= %9.5f\n',ave3);





⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?