我有一个程序,我从教科书中复制,哪些时间在计算与未初始化,初始化的数组和矢量相同的事情时程序执行运行时的差异。在MATLAB中执行定时程序;奇怪的结果
但是,虽然程序运行有点像预期的那样,如果每隔一段时间运行几次,它会发出一个疯狂的结果。请参阅下面的程序和疯狂结果的例子。
clear all; clc;
% Purpose:
% This program calculates the time required to calculate the squares of
% all integers from 1 to 10000 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
% PERFORM CALCULATION WITH AN UNINITIALIZED ARRAY
% (done only once because it is so slow)
maxcount = 1;
tic;
for jj = 1:maxcount
clear square
for ii = 1:10000
square(ii) = ii^2;
end
end
average1 = (toc)/maxcount;
% PERFORM CALCULATION WITH A PRE-ALLOCATED ARRAY
% (averaged over 10 loops)
maxcount = 10;
tic;
for jj = 1:maxcount
clear square
square = zeros(1,10000);
for ii = 1:10000
square(ii) = ii^2;
end
end
average2 = (toc)/maxcount;
% PERFORM CALCULATION WITH VECTORS
% (averaged over 100 executions)
maxcount = 100;
tic;
for jj = 1:maxcount
clear square
ii = 1:10000;
square = ii.^2;
end
average3 = (toc)/maxcount;
% Display results
fprintf('Loop/uninitialized array = %8.6f\n', average1)
fprintf('Loop/initialized array = %8.6f\n', average2)
fprintf('Vectorized = %8.6f\n', average3)
结果 - 正常:
Loop/uninitialized array = 0.195286
Loop/initialized array = 0.000339
Vectorized = 0.000079
结果 - 疯狂:
Loop/uninitialized array = 0.203350
Loop/initialized array = 973258065.680879
Vectorized = 0.000102
这究竟是为什么? (有时疯狂的数字是矢量化的,有时在循环初始化)
MATLAB在哪里“查找”这个数字?
可能是当存储在toc中的时钟值翻转时? – gary 2010-09-07 03:29:44
您使用的是什么MATLAB版本? – gnovice 2010-09-07 03:36:29
@gnovice - 7.10.0.499(2010a) – Rook 2010-09-07 03:38:20