5 ms·
The first example (sum.c) is mistaken: it says the number of iterations per second is 550,000,000, but actually any compiler with -O will remove the loop entire
by comex 11y ago
The first example (sum.c) is mistaken: it says the number of iterations per second is 550,000,000, but actually any compiler with -O will remove the loop entirely (since the sum variable is not used for anything), so the execution time does not depend on the number at all. The answer is limited only by the size of the integer, and the program will always take far less than one second.
- 2bitencryption 11y agoIf the function returned s (the sum number), would it not optimize it away?
- asdfaoeu 11y agoWell so gcc -O2 will just replace the loop with s = NUMBER.
- schoen 11y agoI also confirmed this behavior with disassembly, and now I'm wondering what the basis of this optimization is. Can anyone explain the logic that gcc would have used to do this? As a human, I can see that the loop has no effects except to increase s by 1 each of NUMBER times, and that the result of doing so would increase s by 1 * NUMBER, and that s started as 0, so s ends up as NUMBER. (Also the loop variable i is incremented NUMBER times so it ends up as NUMBER too, but its value is never referred to again.) I'm wondering how the optimizer observed and represented these facts, and how much more general its attempts at optimizing this loop were.
- Gankro 11y agoNot 100% sure but this precise optimization for LLVM is probably part of ScalarEvolution, which tries to figure out how values in a loop evolve: http://llvm.org/devmtg/2009-10/ScalarEvolutionAndLoopOptimization.pdf http://llvm.org/devmtg/2009-10/ScalarEvolutionAndLoopOptimiz... LLVM also has a pass dedicated to detecting loop idioms: http://llvm.org/docs/doxygen/html/LoopIdiomRecognize_8cpp_source.html http://llvm.org/docs/doxygen/html/LoopIdiomRecognize_8cpp_so... (I'm not at all familiar with how GCC is architected, sorry)
- schoen 11y agoCool, thanks for the references!
- AndyKelley 11y agoRelated: https://github.com/computers-are-fast/computers-are-fast.github.io/issues/1 https://github.com/computers-are-fast/computers-are-fast.git...
- schoen 11y agoYou're completely right! Other readers, check it out for yourself with gcc -g sum.c ; echo 'disas main' | gdb ./a.out gcc -g -O2 sum.c ; echo 'disas main' | gdb ./a.out
- dima55 11y agoPro tip: gcc -S -o- sum.c
- schoen 11y agoOh yeah, that assembly already existed in order to create the binary in the first place! Thanks for the tip. (The gdb disassembly shows memory offsets, which might be helpful for some purposes.)
- kragen 11y agoThe best way to do this, which I didn't know about until recently, is gcc -fverbose-asm -g -Wa,-adhln=sum.lst sum.c