AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79495349
Accepted
Ahmed AEK
Ahmed AEK
Asked: 2025-03-09 11:13:31 +0800 CST2025-03-09 11:13:31 +0800 CST 2025-03-09 11:13:31 +0800 CST

为什么虚拟+间接函数调用比虚拟或间接函数调用更快?

  • 772

我试图测量间接的成本,因为将间接堆叠在一起会降低我试图测量的性能。

  1. 直接函数调用(直接调用同一 DLL 中的函数,可能内联)
  2. 间接函数调用(通过指针调用另一个 DLL 中的函数,而不是内联)
  3. 虚函数调用。
  4. 虚函数调用,然后是间接函数调用(保存函数指针的多态类)。

为了防止编译器进行任何内联,我将其拆分exe为dll

可执行代码

#include <limits.h>
#include <vector>
#include <chrono>
#include <iostream>
#include <span>

static int foo(int a, std::vector<int>& v) {
    v.push_back(a);
    if (v.size() > 2)
    {
        v.clear();
    }
    return a;
}

struct IFooable
{
    virtual int foo(int a) = 0;
};

__declspec(dllimport) int foo2(int a, std::vector<int>& v);

__declspec(dllimport) int direct_version(std::vector<int>& v);

__declspec(dllimport) int indirect_version(int (*fn)(int, void*), void* p);

__declspec(dllimport) int indirect_Interface(IFooable& f);

struct MyFoo final: public IFooable
{
    int foo(int a) override
    {
        return ::foo(a, v);
    }
    MyFoo(std::vector<int>& v) : v{ v } {}
    std::vector<int>& v;
};

struct MyFoo2 final : public IFooable
{
    using functype = int (*)(int, std::vector<int>&);
    int foo(int a) override
    {
        return f(a, v);
    }
    MyFoo2(std::vector<int>& v, functype f) : v{ v }, f{ f } {}
    std::vector<int>& v;
    functype f;
};

int main(int argc, char* argv[]) {
    std::vector<int> v;
    for (int i = 0; i < 20; i++)
    {
        foo(i, v);
    }

    std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();

    direct_version(v);
    std::chrono::steady_clock::time_point end1 = std::chrono::steady_clock::now();

    indirect_version([](int a, void* p) {return foo(a, *reinterpret_cast<std::vector<int>*>(p)); }, reinterpret_cast<void*>(&v));
    std::chrono::steady_clock::time_point end2 = std::chrono::steady_clock::now();

    MyFoo ff{ v };
    indirect_Interface(ff);
    std::chrono::steady_clock::time_point end3 = std::chrono::steady_clock::now();
    MyFoo2 ff2{ v, foo2 };
    indirect_Interface(ff2);
    std::chrono::steady_clock::time_point end4 = std::chrono::steady_clock::now();

    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end1 - begin).count() << "[ms] " << "Direct" << std::endl;
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end2 - end1).count() << "[ms] " << "Indirect" << std::endl;
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end3 - end2).count() << "[ms] " << "Virtual" << std::endl;
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end4 - end3).count() << "[ms] " << "Virtual + Indirect" << std::endl;

    double micros_count = std::chrono::duration_cast<std::chrono::milliseconds>(end2 - end1).count();
    double iterations = INT_MAX;
    std::cout << "nanoseconds per iteration = " << (micros_count / iterations) * 1000000 << '\n';
    
    return 0;
}

dll代码

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <vector>
#include <span>

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

struct IFooable
{
    virtual int foo(int a) = 0;
};

static int foo(int a, std::vector<int>& v) {
    v.push_back(a);
    if (v.size() > 2)
    {
        v.clear();
    }
    return a;
}

__declspec(dllexport) int foo2(int a, std::vector<int>& v) {
    v.push_back(a);
    if (v.size() > 2)
    {
        v.clear();
    }
    return a;
}

__declspec(dllexport) int direct_version(std::vector<int>& v) {
    int i, b = 0;
    for (i = 0; i < INT_MAX; ++i) {
        b = foo(b, v);
    }
    return b;
}

__declspec(dllexport) int indirect_version(int (*fn)(int, void*), void* p) {
    int i, b = 0;

    for (i = 0; i < INT_MAX; ++i) {
        b = fn(b, p);
    }

    return b;
}

__declspec(dllexport) int indirect_Interface(IFooable& f) {
    int i, b = 0;

    for (i = 0; i < INT_MAX; ++i) {
        b = f.foo(b);
    }

    return b;
}

它们是在发布模式下编译的,因此/O2,基准测试的构建方式可以避免任何缓存未命中,并且可能允许 CPU 预测所有函数将指向的位置,因为我对分支预测错误或缓存未命中的成本不感兴趣,而且该函数并不简单,但足够小,并且我已经检查了汇编代码,没有任何内容按预期内联。

结果:

3058[ms] Direct
8279[ms] Indirect
9109[ms] Virtual
7340[ms] Virtual + Indirect
nanoseconds per iteration = 3.85521

正如预期的那样,虚拟函数比间接调用稍微慢一些,但是虚拟+间接调用比任何一个都快......这没有意义。

我的问题是,为什么虚拟函数 + 间接寻址比单独使用任何一个都快?我是否应该实际预期这种级联间接寻址的成本会增加?

使用具有虚函数的 C++ API 包装另一个 DLL 中的 C API 的情况并不少见,因此这个基准尽可能接近现实世界。

交换调用的顺序不会改变任何东西,它们也足够长,以至于任何诸如 CPU 加速和过热以及调度程序之类的因素都不会影响基准。


编辑:看起来缓冲区溢出检查稍微歪曲了结果,这是现在没有那些额外检查的较新的结果。

3051[ms] Direct
6182[ms] Indirect
8002[ms] Virtual
7616[ms] Virtual + Indirect
nanoseconds per iteration = 2.87872

虚拟+间接仍然比仅虚拟更快,这非常奇怪。

c++
  • 1 1 个回答
  • 75 Views

1 个回答

  • Voted
  1. Best Answer
    Mingxin Wang
    2025-03-09T12:51:43+08:002025-03-09T12:51:43+08:00

    结果并不“神奇”,而是现代 CPU 和编译器如何处理间接调用、虚拟调用和分支预测的体现。在这样的微基准测试中,单层间接的成本可能受到分支的可预测性以及 CPU 的执行引擎如何流水线处理工作的强烈影响。

    我是Proxy 库的作者,该库实现了无需继承的类型擦除。我也很难创建与虚拟函数(以及标准中的其他类型擦除功能)进行比较的基准。以下是我用来避免意外优化的策略:

    • 将类型缓和对象(具有虚函数、std::any 等的对象)的生产和使用放入单独的翻译单元。类似于您提供的 DLL 解决方案,但没有跨 ABI 调用的额外开销。

    • 交替使用足够多种类型进行测试,以避免产生明显可预测的热点。我为每次调用基准测试使用了 100 种类型。

    • 随机执行足够数量的轮次,以抵消操作系统中不可控的上下文切换造成的抖动。

    请在此处查看我对 Proxy 的基准测试实现。我还实现了一个工具来生成人性化可读的基准测试报告。生成的报告可以在每个 CI 构建(基准测试报告)中找到。这些数字相当稳定。

    • 3

相关问题

  • 为什么编译器在这里错过矢量化?

  • 使用带有库的 CMake 编译错误[关闭]

  • 每次我尝试运行预制时都会抛出错误

  • 如何在 C++ 中创建类似于 std::byte 的八位字节类型?

  • C++17 中 std::byte 只能按位运算?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve