C++: i++ 与 ++i 执行效率测试

在写for循环时,可能大家都会想过是写i++还是++i,表面看两者对for循环并没有什么区别,至于用哪一种

可能更多地是看个人的习惯,笔者之前习惯于使用i++,但是最近看到很多示例代码用的都是++i,我就想到

一个问题,两者用在for循环时,真的没有区别吗?于是我做了一个测试,写了两个for循环,每个循环执行

100000000次,循环中什么都不做,两个循环的区别是一个使用i++,另一个使用++i。

下面是测试程序,测试平台在ubuntu,计算循环所用时间用的是muduo::Timestamp:

#include "Timestamp.h"
#include "iostream"

using namespace muduo;
using namespace std;

int main()
{
  const int cnt = 100000000;

  Timestamp start(Timestamp::now());

  for (int i = 0; i < cnt; i++) {}

  cout << "i++ : " << timeDifference(Timestamp::now(), start) << endl;

  start = Timestamp::now();

  for (int i = 0; i < cnt; ++i) {}

  cout << "++i : " << timeDifference(Timestamp::now(), start) << endl;
  
  start = Timestamp::now();
  
  for (int i = 0; i < cnt; i++) {}

  cout << "i++ : " << timeDifference(Timestamp::now(), start) << endl;

  start = Timestamp::now();

  for (int i = 0; i < cnt; ++i) {}

  cout << "++i : " << timeDifference(Timestamp::now(), start) << endl;
  
  return 0;
}

运行结果:

root@ubuntu:/home/wangml/code/muduo_test# g++ Timestamp.cc i_test.cc -o i_test
root@ubuntu:/home/wangml/code/muduo_test# ./i_test 
i++ : 0.167789
++i : 0.045245
i++ : 0.169432
++i : 0.044357

可以看到使用++i的循环所耗费的时间是使用i++循环的四分之一作用。

转载请注明出处
原文地址:https://www.cnblogs.com/lnlin/p/14553690.html