Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

for(loops)

Name: Anonymous 2010-10-22 16:52



int main(void) {
  for(int n=0;n!=50;n++)
    cout << "Hello, world no. %d\n" << n << endl;
}

int main(void) {
  for(int n=0;n!=50;++n)
    cout << "Hello, world no. %d\n" << n << endl;
}

int main(void) {
  for(int n=0;n!=50;n=n+1)
    cout << "Hello, world no. %d\n" << n << endl;
}

int main(void) {
  for(int n=0;n!=50;n+=1)
    cout << "Hello, world no. %d\n" << n << endl;
}


The second code runs fastest, followed by the first code, then the third and fourth tied. I though these were logically the same? Why the speed difference.

Name: Anonymous 2010-10-23 17:21

I don't even know how many times I've seen this stupid thread on /prog/, or more precisely the thread discussing performance differences between post/pre increment/decrement operators.

The generated code is usually the same most of the time, however it depends on a variety of factors:if you are going to use the value after the operation, the rest of the code (seemingly unrelated, but affects register allocation and overall allocation strategy for the variables in your function), the compiler (and what kinds of optimizations can it perform(dataflow, SSA, etc)), its optimization settings. In the rare cases when the generated code is different, most of the time, the differences are very tiny, such as one extra instruction (such as an extra mov), usually such instructions could even be executed in parallel by some modern CPUs when possible, thus this has no real effect on speed, however on other CPUs it might have a very minor effect. Then you have larger differences which are unrelated to your code at all, such as the OS and its scheduler (realtime or not), which is likely where your apparently speed differences come from - calculating the errors induced by the scheduler is important, but you'll find out that you won't really be able to notice a real difference in performance unless you run it an outrageous amount of time, but then you also have to factor in benchmarking errors and whatnot.

So the answer to OP's question is that the difference in performance is either inexistent, or is incredibly tiny and platform specific and he should never, ever worry about it in practice.

>>6's joke answer somehow even feels appropriate here, because OP is trying to measure something he does not really understand, and something which might not even exist in the generated code (depends on his compiler, etc). It reminds me of silly things like talks of consciousness in microtubules...

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List