MATLAB中的定时程序执行; 奇怪的结果

Roo*_*ook 10 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)
Run Code Online (Sandbox Code Playgroud)

结果 - 正常:

Loop / uninitialized array = 0.195286
Loop / initialized array =   0.000339
Vectorized =                 0.000079
Run Code Online (Sandbox Code Playgroud)

结果 - 疯狂:

Loop / uninitialized array = 0.203350
Loop / initialized array =   973258065.680879
Vectorized =                 0.000102
Run Code Online (Sandbox Code Playgroud)

为什么会这样? (有时候疯狂的数字是矢量化的,有时是在循环初始化的)

MATLAB在哪里"找到"那个数字?

zel*_*lus 1

至少有两个可能的误差源。您可以尝试通过仅查看计算值而不对其进行格式化来区分“tic/toc”和“fprintf”吗?

我不明白“toc”周围的大括号,但它们不应该造成任何伤害。