c++11 - C++ run time with different loops -


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

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

i get, time, following results: time ./test 1 loop

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

and

two loops

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

i did research , said cause of branching i'm not sure if reason, compiled

g++ -std=c++11 -o3 test.cpp -dsingle -o test 

the overall loop barely puts dent, in modern, multi-gigahertz cpus, enormous level 1 & 2 cpu caches, , blazingly fast memory.

you're going have come 2 alternative execution paths have way, way, more substantive differences, single, puny if() statement that, before can see kind of difference.

think of way: modern cpus have sorts of crazy pipelining, make possible cpu execute not current instruction, several instructions after that. @ same time. when current instruction loop increment, cpu has figured out next if() evaluate to, , after that. during same set of clock cycles.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

c++ - Clear the memory after returning a vector in a function -

erlang - Saving a digraph to mnesia is hindered because of its side-effects -