我有一個程序,我從教科書中複製,哪些時間在計算與未初始化,初始化的數組和矢量相同的事情時程序執行運行時的差異。在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