日志打印传值 传引用 右值引用性能测试(Linux/QNX)

发布于:2024-05-10 ⋅ 阅读:(24) ⋅ 点赞:(0)

结论

Linux平台和qnx平台优化后传值性能都是比传引用的差,也比传右值的差,因此传参时有必要传递引用。

测试代码

#include <cstdint>
#include <ctime>
#include <string>

#ifdef __linux__
    #define ITERATIONS 10000000
#else
    #define ITERATIONS 100000
#endif

template <typename... ARGS_TYPE>
void my_log_value(const std::string &fmt_str, ARGS_TYPE... fmt_args) {
  printf(fmt_str.c_str(), fmt_args...);
}

template <typename... ARGS_TYPE>
void my_log_reference(const std::string &fmt_str, ARGS_TYPE const &... fmt_args) {
  printf(fmt_str.c_str(), fmt_args...);
}

template <typename... ARGS_TYPE>
void my_log_rvalue(const std::string &fmt_str, ARGS_TYPE &&... fmt_args) {
  printf(fmt_str.c_str(), std::forward<ARGS_TYPE>(fmt_args)...);
}

int main() {
  // Test pass by value
  uint64_t num64 = 1234567890;
  uint32_t num32 = 987654321;
  int32_t int32 = -12345;
  const char *str = "hello, world";
  char ch = 'A';
  float fl = 3.14159f;
  {
    clock_t startVal = clock();
    for (int i = 0; i < ITERATIONS; ++i) {
      my_log_value("value: %lu, %u, %d, %s, %c, %f\n", num64, num32, int32, str, ch, fl);
    }
    clock_t endVal = clock();
    double elapsedVal = static_cast<double>(endVal - startVal) / CLOCKS_PER_SEC;
    printf("Pass by value: %f seconds\n", elapsedVal);
  }
  {
    // Test pass by reference
    clock_t startRef = clock();
    for (int i = 0; i < ITERATIONS; ++i) {
      my_log_reference("value: %lu, %u, %d, %s, %c, %f\n", num64, num32, int32, str, ch, fl);
    }
    clock_t endRef = clock();
    double elapsedRef = static_cast<double>(endRef - startRef) / CLOCKS_PER_SEC;
    printf("Pass by reference: %f seconds\n", elapsedRef);
  }
  {
    // Test pass by rvalue reference
    clock_t startRValue = clock();
    for (int i = 0; i < ITERATIONS; ++i) {
      my_log_rvalue("value: %lu, %u, %d, %s, %c, %f\n", num64, num32, int32, str, ch, fl);
    }
    clock_t endRValue = clock();
    double elapsedRValue = static_cast<double>(endRValue - startRValue) / CLOCKS_PER_SEC;
    printf("Pass by rvalue: %f seconds\n", elapsedRValue);
  }

  return 0;
}


编译指令

+ Linux平台

编译: g++ -o test test.cpp -std=c++11 -O2

执行结果:
在这里插入图片描述

+ QNX 710

编译
/opt/qos222/host/linux/x86_64/usr/bin/aarch64-unknown-nto-qnx7.1.0-g++ -o test test.cpp -O2
执行结果:
在这里插入图片描述