gpt4 book ai didi

Matlab:for 循环向量。奇怪的速度行为?

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:37 27 4
gpt4 key购买 nike

我在 matlab 上玩了一下 for 循环,我知道通常可以避免它们,在这种情况下,速度要快得多。但是如果我真的想遍历向量 V 的所有元素,我做了那个小测试:

n=50000000;
V =1:n;

s1 = 0;
tic
for x=V
s1 = s1+x;
end
toc

s2 = 0;
tic
for ind=1:numel(V)
s2 = s2+V(ind);
end
toc

s1 和 s2 相等(正常),但第一个循环需要 24.63 秒,第二个循环只需要 0.48 秒。

我对这些数字感到有点惊讶。它是已知的吗?有没有人有任何解释?

最佳答案

这可能是由内存分配引起的。案例1中的陈述,

for x=V

必须创建 V 的副本。我们为什么知道?如果您在循环中修改 Vx 将不会受到影响:它仍将运行原始 V 值。

另一方面,案例2中的陈述,

for ind=1:numel(V)

实际上并不创建向量1:numel(V)。来自帮助

Long loops are more memory efficient when the colon expression appears in the for statement since the index vector is never created.

不需要分配内存这一事实可能至少部分地解释了速度的提高。

为了对此进行测试,让我们将 for ind=1:numel(V) 更改为 for ind=[1:numel(V)]。这将强制创建向量 1:numel(V)。那么运行时间应该与情况 1 相似,或者确实更大一些,因为我们仍然需要使用 V(ind) 索引到 V

这些是我电脑上的运行时间:

% Case 1
n=50000000;
V =1:n;
s1 = 0;
tic
for x=V
s1 = s1+x;
end
toc

% Case 2
s2 = 0;
tic
for ind=1:numel(V)
s2 = s2+V(ind);
end
toc

% Case 3
s3 = 0;
tic
for ind=[1:numel(V)]
s3 = s3+V(ind);
end
toc

结果:

Elapsed time is 0.610825 seconds.
Elapsed time is 0.182983 seconds.
Elapsed time is 0.831321 seconds.

关于Matlab:for 循环向量。奇怪的速度行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746680/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com