为什么(在MATLAB中)这段代码更快?

NKN*_*NKN 5 performance matlab

我在MATLAB中用两种不同的方式编写了一些代码.首先,我使用了两个for循环,乍一看似乎很愚蠢:

Initial = [zeros(10,1) ones(10,1)];

for xpop=1:10
    for nvar=1:10
        Parent(xpop,nvar) = Initial(nvar,1)+(Initial(nvar,2)-Initial(nvar,1))*rand();
    end
end
Run Code Online (Sandbox Code Playgroud)

在第二个方案中,我尝试进行矢量化计算(我假设它可以更快):

Parent = repmat(Initial(:,1),1,10) + rand(10,10).*(repmat(Initial(:,2),1,10)-repmat(Initial(:,1),1,10));
Run Code Online (Sandbox Code Playgroud)

可以在以下三个不同的代码运行中看到经过的时间:

Elapsed time is 0.000456 seconds.
Elapsed time is 0.006342 seconds.

Elapsed time is 0.000457 seconds.
Elapsed time is 0.006147 seconds.

Elapsed time is 0.000471 seconds.
Elapsed time is 0.006433 seconds.
Run Code Online (Sandbox Code Playgroud)

为什么第一个方案比第二个方案更快?它真的在'.*'命令中为循环做了两个愚蠢的事吗?

Mar*_*sen 9

您的测试设置太小,无法显示矢量化的优势.

Initial = [zeros(10,1) ones(10,1)];
Elapsed time is 0.000078 seconds.
Elapsed time is 0.000995 seconds.
Run Code Online (Sandbox Code Playgroud)

现在有一个更大的问题:

Initial = [zeros(1000,1) ones(1000,1)];
Elapsed time is 2.797949 seconds.
Elapsed time is 0.049859 seconds.
Run Code Online (Sandbox Code Playgroud)

  • 我会说_heavily_取决于所执行的确切操作. (5认同)
  • @KronoS实际上,使用一个击败向量化等价的循环很少会使你的总代码运行时间缩短一秒.另一方面,良好的矢量化通常可以节省数秒或更多.因此,除非您正在优化被称为大量时间的事情,否则不要费心测试循环以获得性能. (2认同)