这是更快? "结构&QUOT的载体;或QUOT;一些载体"? [英] which is faster? "vector of structs" or "a number of vectors"?

查看:197
本文介绍了这是更快? "结构&QUOT的载体;或QUOT;一些载体"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案1: 如果我有一类类似,

Solution 1: If i have a class like,

class car{ public: int a; string b; bool c;};

我可以建立的200辆汽车的矢量:

i can build a vector of 200 cars:

std::vector<car>   allcas;  
allcars.resize(200)

在运行时,我只是做:

at runtime, i just do:

this_car=allcars[102];

然后......

then ....

解决方案2:

我有

std::vector<int> a; a.resize(200);
std::vector<string>b; b.resize(200);
std::vector<bool> c; c.resize(200);

this_car_a = a[102];
this_car_b = b[102];
this_car_c = c[102];

问: 哪一个是更快?

Question: Which one is faster?

有没有人有一个想法?感谢很多提前!

Does anyone have an idea? thanks a lot in advance!

推荐答案

一个载体结构有几个优势超过了结构向量:

A "struct of vectors" has a couple of advantages over a "vector of structs":

  • 如果您内环不使用该结构的每一个元素,那么-的结构向量可以节省内存带宽,为未使用元素的载体将不会被加载到缓存。
  • 这是比较容易向量化。基于结构的向量可以使您使用的处理器的向量处理指令(通过组装,内联函数,或聪明的编译器),以加快您的内部循环。

在另一方面,premature的优化是一切罪恶的根源:

On the other hand, premature optimization is the root of all evil:

  • 使用结构 - - 向量是比较困难的,尴尬的,并不起眼。
  • 您通常不知道你的性能瓶颈,直到你有你的code启动和运行。是否值得让你的code更详细,脆弱,难吗?你不会知道,直到你实际配置文件了。
  • 结构-的矢量编程的好处按个别情况而有所不同。它并不总是产生一个加速;你实际上可以结束了糟糕的表现。
  • 在特定的,如果你的访问模式是随机的(相对于顺序或以其他方式本地化)结构,即用向量的组织最终可能装载太多的更多的从内存中无用的数据,如果每个高速缓存行包含来自多个附近的对象...
  • 元素
  • Using a struct-of-vectors is more difficult, awkward, and obscure.
  • You generally don't know where your performance bottlenecks are until you've got your code up and running. Is it worth making your code more verbose, fragile, and difficult? You won't know until you actually profile it.
  • The benefits of struct-of-vectors programming vary on a case by case basis. It doesn't always yield a speedup; you could actually end up with worse performance.
  • In particular, if your access pattern is random (as opposed to sequential or otherwise localized) a struct-of-vectors organization could end up loading much more useless data from memory, if each cache line includes elements from multiple nearby objects...

所以,我的建议是使用矢量的-结构默认,但牢记结构-的向量作为替代(即,确保您​​可以在以后切换,如果你期望的顺序/本地访问模式,它不费多大力气了前面)。一旦你的程序运行,你可以分析它,看看那里的性能关键部分是,并尝试了结构-的矢量和矢量运算,他们会做最擅长的。

So, my recommendation is to use vector-of-structs by default, but keep struct-of-vectors in mind as an alternative (i.e., make sure you can switch later, if you expect sequential/local access patterns and it doesn't cost much effort up front). Once your program is running, you can profile it to see where the performance-critical sections are, and try out struct-of-vector and vectorized operations where they'll do the most good.

这篇关于这是更快? &QUOT;结构&QUOT的载体;或QUOT;一些载体&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆