C++虚函数调用与 boost::function 快速调用

发布于 2024-08-19 20:40:32 字数 236 浏览 8 评论 0原文

我想知道与同一个 boost::function 调用相比,单继承虚函数调用有多快。它们的性能几乎相同还是 boost::function 更慢?

我知道性能可能因情况而异,但是,作为一般规则,哪个更快,速度有多大?

谢谢, Guilherme

-- 编辑

KennyTM 的测试对我来说足够有说服力。出于我自己的目的, boost::function 似乎并不比 vcall 慢多少。谢谢。

I wanted to know how fast is a single-inheritance virtual function call when compared to one same boost::function call. Are they almost the same in performance or is boost::function slower?

I'm aware that performance may vary from case to case, but, as a general rule, which is faster, and to a how large degree is that so?

Thanks,
Guilherme

-- edit

KennyTM's test was sufficiently convincing for me. boost::function doesn't seem to be that much slower than a vcall for my own purposes. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九厘米的零° 2024-08-26 20:40:32

作为一种非常特殊的情况,请考虑调用空函数 109 次。


代码A:

struct X {
            virtual ~X() {}
        virtual void do_x() {};
};
struct Y : public X {}; // for the paranoid.

int main () {
        Y* x = new Y;
        for (int i = 100000000; i >= 0; -- i)
                x->do_x();
        delete x;
        return 0;
}

代码B:(使用boost 1.41):

#include <boost/function.hpp>

struct X {
    void do_x() {};
};

int main () {
    X* x = new X;
    boost::function<void (X*)> f;
    f = &X::do_x;
    for (int i = 100000000; i >= 0; -- i)
        f(x);
    delete x;
    return 0;
}

g++ -O3编译,然后用time计时,

  • 代码A需要0.30秒。
  • 代码 B 需要 0.54 秒。

检查汇编代码,似乎缓慢可能是由于异常和处理可能性造成的,并且 f 可以为 NULL。但考虑到一次 boost::function 调用的时间仅为 2.4 纳秒(在我的 2 GHz 机器上),do_x() 中的实际代码可能会掩盖这一点。我想说,这不是避免使用 boost::function 的理由。

As a very special case, consider calling an empty function 109 times.


Code A:

struct X {
            virtual ~X() {}
        virtual void do_x() {};
};
struct Y : public X {}; // for the paranoid.

int main () {
        Y* x = new Y;
        for (int i = 100000000; i >= 0; -- i)
                x->do_x();
        delete x;
        return 0;
}

Code B: (with boost 1.41):

#include <boost/function.hpp>

struct X {
    void do_x() {};
};

int main () {
    X* x = new X;
    boost::function<void (X*)> f;
    f = &X::do_x;
    for (int i = 100000000; i >= 0; -- i)
        f(x);
    delete x;
    return 0;
}

Compile with g++ -O3, then time with time,

  • Code A takes 0.30 seconds.
  • Code B takes 0.54 seconds.

Inspecting the assembly code, it seems that the slowness may be due to exceptions and handling the possibility and that f can be NULL. But given the price of one boost::function call is only 2.4 nanoseconds (on my 2 GHz machine), the actual code in your do_x() could shadow this pretty much. I would say, it's not a reason to avoid boost::function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文