⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 timings.m

📁 matlab源代码,适用于开发研究,带来很好的学习效果.
💻 M
字号:
% Script file timings.m
%
% 目的:
%   该段程序代码需要计算使用三种
%  不同方法计算从1到10,000的整数 
%  平方的时间:
%  1.不使用初始化数组的数值
%  2.使用初始化的数组数值
%  3.使用向量化.

% 定义变量
% ii,jj       循环次数
% ave1     第一种方法的平均时间
% ave2     第二种方法的平均时间
% ave3     第三种方法的平均时间
% maxcount 循环计算的次数
% square   平方数值的数组

%不预先设定数组,直接求解结果
maxcount=1;
tic;
for jj=1:maxcount
clear square
for ii=1:10000
    square(ii)=ii^2;
end
end
ave1=(toc)/maxcount;

%预先设定空数组,计算循环
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;

%使用程序的向量化
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);
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -