速度差异:在一个大类中使用 *this 单独的仿函数 VS 运算符()
我正在使用 c++ STL 堆算法,并且我围绕它编写了一个包装类,这样我就可以做一些其他的事情。例如,当我尝试使用下面的代码时:
//! Min-heap wrapper class.
class FMMHeap{
public:
FMMHeap(Vector &phi) : _phi(phi) {}
bool operator()(unsigned p1, unsigned p2) {return fabs(_phi(p1)) > fabs(_phi(p2)); }
inline void pop(){ pop_heap(_heap.begin(),_heap.end(),*this); _heap.pop_back(); }
[...lots of other stuff...]
vectorU32 _heap;
Vector &_phi;
}
它比我有一个像这样的单独函数对象时慢得多:
struct HeapSort{
public:
HeapSort(Vector &phi) : _phi(phi) {}
bool operator()(unsigned p1, unsigned p2) {return fabs(_phi(p1)) > fabs(_phi(p2)); }
private:
Vector &_phi;
};
class FMMHeap{
public:
FMMHeap(Vector &phi) : cmp(phi) {}
inline void pop(){ pop_heap(_heap.begin(),_heap.end(),cmp); _heap.pop_back(); }
[...lots of other stuff...]
vectorU32 _heap;
HeapSort cmp;
}
我不确定为什么会这样。速度减慢是否来自 *this 因为该类有大量数据?这看起来很奇怪。还是与函数对象的使用方式有关?
I'm using the c++ STL heap algorithms, and I wrote a wrapper class around it so I could do some other stuff. When I tried to use the code below, for example:
//! Min-heap wrapper class.
class FMMHeap{
public:
FMMHeap(Vector &phi) : _phi(phi) {}
bool operator()(unsigned p1, unsigned p2) {return fabs(_phi(p1)) > fabs(_phi(p2)); }
inline void pop(){ pop_heap(_heap.begin(),_heap.end(),*this); _heap.pop_back(); }
[...lots of other stuff...]
vectorU32 _heap;
Vector &_phi;
}
It was wayyyyy slower than when I had a separate function object like this:
struct HeapSort{
public:
HeapSort(Vector &phi) : _phi(phi) {}
bool operator()(unsigned p1, unsigned p2) {return fabs(_phi(p1)) > fabs(_phi(p2)); }
private:
Vector &_phi;
};
class FMMHeap{
public:
FMMHeap(Vector &phi) : cmp(phi) {}
inline void pop(){ pop_heap(_heap.begin(),_heap.end(),cmp); _heap.pop_back(); }
[...lots of other stuff...]
vectorU32 _heap;
HeapSort cmp;
}
I'm not sure why this is. Is the slowdown coming from *this because the class has a lot of data? That seems odd. Or is it something to do with how the function object is used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定:但也许
pop_heap
最终会复制您传入的函子对象。FMMHeap
的副本比简单的HeapSort
更昂贵I'm not certain: but maybe
pop_heap
ends up copying the functor object you pass in.The copy for your
FMMHeap
would be more expensive than the simpleHeapSort
STL 容器的最大加速是它们的内联,这样编译器就可以计算出如何删除和重新排序内容。
这是一个很好的猜测,编译器设法以 const 传播阻止它在慢速版本中这样做的方式内联外部函子。
如果 bool 运算符是 const,慢速版本会发生什么?
The biggest speedup of the STL containers is the inlining of them, such that the compiler can work out how to remove and reorder things.
Its a good guess that the compiler manages to inline the external functor in a way that const propogation is stopping it from doing so in the slow version.
What happens to the slow version if the bool operator is const?