dimanche 28 février 2016

C++ run time with different loops

Why do both of these loops take the same amount of time, shouldn't the if statement make the first single loop much slower?

// Example program                                                                                     
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
  int counter = 0;
  #ifdef single
  cout << "one for loop\n";
  for(int i =0;i<10000000;i++)
    {
      if(i != 50000) counter+=i;
    }
#else
  cout << "two loops\n";
  for(int i = 0;i<50000;i++)
    {
      counter+=i;
    }
  for(int i = 50001;i<10000000;i++)
    {
      counter+=i;
    }
#endif
  return 0;
}

I get, for time, the following results: time ./test one for loop

real 0m0.004s user 0m0.001s sys 0m0.002s

AND

two loops

real 0m0.004s user 0m0.001s sys 0m0.002s

I did some research and it said it is cause of branching but I'm not sure if that is the only reason, it was compiled as

g++ -std=c++11 -O3 test.cpp -Dsingle -o test

Aucun commentaire:

Enregistrer un commentaire