英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论