简体   繁体   English

高维数组与C ++中的一维数组效率

[英]Higher dimensional array vs 1-D array efficiency in C++

I'm curious about the efficiency of using a higher dimensional array vs a one dimensional array. 我对使用高维数组与一维数组的效率感到好奇。 Do you lose anything when defining, and iterating through an array like this: 在定义和遍历这样的数组时,您是否会丢失任何东西:

array[i][j][k];

or defining and iterating through an array like this: 或定义和遍历这样的数组:

array[k + j*jmax + i*imax];

My inclination is that there wouldn't be a difference, but I'm still learning about high efficiency programming (I've never had to care about this kind of thing before). 我的倾向是不会有什么区别,但是我仍在学习高效编程(以前我从来不需要关心这种事情)。

Thanks! 谢谢!

The only way to know for sure is to benchmark both ways (with optimization flags on in the compiler of course). 唯一可以确定的方法是对这两种方法进行基准测试(当然,在编译器中启用了优化标志)。 The one think you lose for sure in the second method is the clarity of reading. 一个人认为您肯定会在第二种方法中迷失的是阅读的清晰度。

The former way and the latter way to access arrays are identical once you compile it. 编译后,访问数组的前一种方法和后一种方法是相同的。 Keep in mind that accessing memory locations that are close to one another does make a difference in performance, as they're going to be cached differently. 请记住,访问彼此接近的内存位置确实会影响性能,因为它们将以不同的方式缓存。 Thus, if you're storing a high-dimensional matrix, ensure that you store rows one after the other if you're going to be accessing them that way. 因此,如果要存储高维矩阵,请确保以这种方式访问​​行,然后一个接一个地存储行。

In general, CPU caches optimize for temporal and spacial ordering. 通常,CPU缓存针对时间和空间顺序进行优化。 That is, if you access memory address X, the odds of you accessing X+1 are higher. 也就是说,如果您访问内存地址X,则访问X + 1的几率会更高。 It's much more efficient to operate on values within the same cache line. 对同一高速缓存行中的值进行操作效率更高。

Check out this article on CPU caches for more information on how different storage policies affect performance: http://en.wikipedia.org/wiki/CPU_cache 请查看有关CPU缓存的本文,以获取有关不同存储策略如何影响性能的更多信息: http : //en.wikipedia.org/wiki/CPU_cache

If you can rewrite the indexing, so can the compiler. 如果您可以重写索引,那么编译器也可以。 I wouldn't worry about that. 我不会担心的。

Trust your compiler(tm)! 相信您的编译器(TM)!

它可能取决于实现,但是我想说它或多或少等于您的一维数组代码。

Do yourself a favor and care about such things after profiling the code . 对代码进行概要分析后,请帮自己一个忙,并关心此类事情。 It is very unlikely that something like that will affect the performance of the application as a whole. 这样的事情不太可能会影响整个应用程序的性能。 Using the correct algorithms is much more important 使用正确的算法更为重要

And even if it does matter, it is most certainly only a single inner loop that needs attention. 即使确实很重要,也绝对需要关注的只是一个内部循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM