【问题标题】:C++ inline performance decreaseC++ 内联性能下降
【发布时间】:2020-08-11 10:39:49
【问题描述】:

我一直在尝试找出将字节向量更改为 64 位整数的最快方法,这是我用于基准测试的代码

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>
#include <cstring>
#include <vector>
#include <cstdint>

template<typename TimeT = std::chrono::milliseconds>
struct measure
{
    template<typename F, typename ...Args>
    static typename TimeT::rep execution(F func, Args&&... args)
    {
        auto start = std::chrono::high_resolution_clock::now();
        func(std::forward<Args>(args)...);
        auto duration = std::chrono::duration_cast< TimeT>
                (std::chrono::high_resolution_clock::now() - start);
        return duration.count();
    }
};

inline void test()
{
    std::vector<uint8_t> bytes = { 0xd4, 0xf0, 0xfe, 0xff};

    int64_t value = 0;
    

    unsigned shift = (bytes.size() - 1) * 8;

    for (int i = 0; i < bytes.size(); i--) {
        value = value | (((int64_t)bytes[i] & 0xff) << shift);
        shift -= 8;
    }
}

int main ()
{
    using namespace std::chrono;

    uint64_t total = 0;

    for (int i = 0; i < 10000; ++i)
    {
        auto t = measure<std::chrono::nanoseconds>::execution(test);
        total += t;
    }    

    std::cout << "Done in " << (total / 10000) << " ns." << std::endl;

    return 0;
}

我在我的机器上得到的结果大约是 150 NS,但是当我在函数之前删除 inline 关键字时,时间会下降到 50ns。所以我的问题是——我什么时候应该避免内联函数(什么时候会降低性能)。

我用它编译过

clang++ main.cpp -o main -O3 -std=c++17

【问题讨论】:

  • 从矢量数据到int64_tmemcpy不是更快吗?
  • 您的基准测试有缺陷。在我的机器上,这两个执行时间都在 ~50 到 150ns 之间。尝试使用更多迭代并确保您的 C 编译器不会优化
  • @Bathsheba memcpy 更快,但是我必须处理字节序
  • @DanielNowak:我处理这个问题的方式是使用#ifdefs,注意 Unix 方式是序列化的标准方式。
  • @Bathsheba:字节序的“Unix方式”?嗯?我认为 Unix 是在 either 字节序上运行的... ;-)

标签: c++ performance function inline inline-functions


【解决方案1】:

您似乎在测量噪音。

您粘贴到https://godbolt.org/ 的代码没有变化;该值由编译器预先计算。也就是说,在我修改了你的test() 以返回该值之后,否则它被优化了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多