C ++内联性能下降

问题描述

我一直在尝试找出将字节向量更改为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

解决方法

您似乎正在测量噪声。

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