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

结论

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
执行结果:
在这里插入图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橘色的喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值