0

Thanks to "Ry-", this is probably a duplicate of Empty loop is slower than a non-empty one in C

I wrote following c++ code:

#include <iostream>
#include <ctime>

void step() {
    return;
}
void loop(int n) {
    for (int i = 0; i < n; i++) {
        step();
    }
    return;
}
int main(int argc, char** argv) {
    clock_t tic = clock();
    loop(int(1e9));
    clock_t toc = clock();
    std::cout << "elapsed in " << double(toc-tic)/CLOCKS_PER_SEC << " " << "seconds" << std::endl;
    return 0;
}

Then I compiled it with -O0 flag. The printout is

elapsed in 1.23771 seconds

If I remove the "step" function, leaving an empty loop, the printout becomes

elapsed in 2.72871 seconds

It's curious to see that an empty loop is slower than a loop that "does nothing". Does anyone know what's happening here?

yxie
  • 27
  • 3
  • Sorry, wrote it wrong. It's the one without function call that runs slower. Just corrected. – yxie May 15 '18 at 00:08
  • @yxie The intermediate IL/"asm" shows what? – user2864740 May 15 '18 at 00:09
  • 4
    [Can reproduce](http://coliru.stacked-crooked.com/a/2ffddddf9056f8f5). That said, benchmarking unoptimized code is pretty useless. – NathanOliver May 15 '18 at 00:11
  • 2
    Probably https://stackoverflow.com/questions/25068032/empty-loop-is-slower-than-a-non-empty-one-in-c, https://stackoverflow.com/questions/45442458/loop-with-function-call-faster-than-an-empty-loop, https://stackoverflow.com/questions/49189685/adding-a-redundant-assignment-speeds-up-code-when-compiled-without-optimization – Ry- May 15 '18 at 00:15
  • 1
    It's only meaningful to bechmark fully optimized code. `-O0` is basically "don't even try, just half-ass it". If you're curious why it's slower, look at the assembler output from both versions. – tadman May 15 '18 at 00:31
  • @Ry- Thank you. That's indeed what I am looking for! – yxie May 15 '18 at 00:31

0 Answers0