这种变化会导致不同的性能表现吗?

huangapple go评论75阅读模式
英文:

How does this change lead to different performance?

问题

我刚刚在卡内基梅隆大学的2015年秋季《计算机系统导论》讲座中发现了这个。这是错误的吗?因为它与交换了int变量的代码完全相同。请帮忙解释一下。感谢任何解释。

英文:

I've just stumbled upon this from 2015 Fall: 15-213 Introduction to Computer Systems lecture by Carnegie Mellon University.

这种变化会导致不同的性能表现吗?

Is this incorrect? Because it's exactly the same code with swapped int variables. Please help. I appreciate any explanation here.

答案1

得分: 4

让我们来看一个小而简单的“2D”数组:

int a[2][2];

在内存中,它的布局如下:
<pre>
+---------+---------+---------+---------+
| a[0][0] | a0 | a[1][0] | a1 |
+---------+---------+---------+---------+
</pre>

在循环的第一个变体中,你按照a[0][0]a[0][1]a[1][0]a[1][1]的顺序进行迭代。你迭代的是彼此相邻的元素,因此它们在缓存中。

在第二个变体中,你按照a[0][0]a[1][0]a[0][1]a[1][1]的顺序进行迭代。

看到第二个变体中如何来回跳跃了吗?当数组变得更大时,这会导致CPU需要更频繁地从内存中获取数据,因为无法将所有数据都放入缓存中。更多的内存访问导致效率降低和执行时间变长。

英文:

Lets take a small and simple "2D" array:

int a[2][2];

In memory it's laid out like this:
<pre>
+---------+---------+---------+---------+
| a[0][0] | a0 | a[1][0] | a1 |
+---------+---------+---------+---------+
</pre>

In the first variant of the loops, you iterate in the order a[0][0], a[0][1], a[1][0], and a[1][1]. You iterate over the elements that are close together, so they are in the cache.

In the second variant you iterate in the order a[0][0], a[1][0], a[0][1], and a[1][1].

See how you jump back and forth in the second variant? When the arrays are larger, this will make the CPU need to fetch data from memory more often, since it's no longer possible to fit it all into the cache. More memory access leads to lower efficiency and longer execution times.

huangapple
  • 本文由 发表于 2023年2月27日 17:26:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578689.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定