在 C++ 中使用代数结构矩阵类的开销;
我正在使用C++编写一些复杂的FFT算法,因此我需要实现四元数和汉密尔顿-爱森斯坦代码等代数结构。算法适用于该结构的二维数组。将它们实现为类的开销是多少?换句话说,我应该创建由四元数类组成的 [M][N] 维度数组,还是应该创建 [M][N][4] 数组并将 [4] 数组用作四元数?使用类更方便,但是创建 M*N 类并访问它们的方法而不是仅使用数组 - 这不是太多的开销吗?我正在编写用于大图像处理的算法,因此性能对我来说很重要。
I am using C++ to code some complicated FFT algorithm, so I need to implement such algebraic structures as quaternions and Hamilton-Eisenstein codes. Algorithm works with 2D array of that structures. What would be the overhead of implementing them as classes? In other way, should I create the array with [M][N] dimensions which consists of Quaternion classes, or should I create [M][N][4] array and work with [4] arrays as quaternions? Using classes is more convenient, but creating M*N classes and accessing their methods instead of working with just array - wouldn't that be too much overhead? I'm coding the algorithm for large images processing, so performance is important for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
恕我直言,将它们实现为类会更好,因为这会让您更快地编写代码并减少错误。如果这对您很重要,您应该进行测量,看看什么执行得最好,但也要确保该代码实际上是性能瓶颈。 (强制Donald Knuth 引用:“过早的优化是万恶之源”)。
我想说,大多数编译器都会很好地为您优化代码。我经常发现,除了这些低级的事情之外,还有其他一些事情会产生影响,比如添加提前测试或最小化数据集等等。
对于四元数,您仍然可以在内部使用数组来实现该类(如果实际上更快),这应该使差异变得不那么重要。
例如,确保可以在多核计算机上并行运行算法或使用 SSE 指令进行实际计算,可能会为您提供更好的服务。
IMHO you are better served by implementing them as classes simply because this will let you write your code quicker with less errors. You should do measurements to see what performs best if that is important for you, but also make sure that it is actually this code that is the performance bottleneck. (Mandatory Donald Knuth quote: "premature optimization is the root of all evil").
Most compilers will do a very good job at optimizing code for you, I would say. More often than not I find that it is something else than these low level things that make a difference, like adding an early-out test or minimizing the dataset or whatnot.
For a quaternion, you can still implement the class using an array internally (in case that is actually faster), which should make the difference even less important.
You are probably better served by for instance making sure that you can run your algorithms in parallell on multicore machines or make your actual calculations use SSE instructions.
关于类的开销:除非您的类具有虚函数,否则使用类不会有任何损失。
因此,例如,复杂变量的数组可以写为:
不过,要注意 STL 集合类,因为它们倾向于使用动态分配,有时会引入显着的开销(即,我不会使用
vector< 来创建数组)。 。
您可能想要研究 Eigen 用于快速、优化的矩阵/向量类。
Regarding overhead of classes: Unless your classes have virtual functions, there's no penalty for using classes.
So, for example, an array of complex variables may be written as:
Beware of STL collection classes, though, as they tend to use dynamic allocation and sometimes introduce significant overhead (i.e., I wouldn't make arrays using
vector< vector<> >
.You might want to investigate the use of a library such as Eigen for fast, optimized, matrix/vector classes.