6

While playing with VS11 beta I noticed something weird: this code couts

f took 0 milliseconds

int main()
{
    std::vector<int> v;
    size_t length =64*1024*1024;
    for (int i = 0; i < length; i++)
    {
        v.push_back(rand());
    }

    uint64_t sum=0;
    auto t1 = std::chrono::system_clock::now();
    for (size_t i=0;i<v.size();++i)
        sum+=v[i];
    //std::cout << sum << std::endl;
    auto t2 = std::chrono::system_clock::now();
    std::cout << "f() took "
        << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
              << " milliseconds\n";


}

But when I decide to uncomment the line with couting of the sum then it prints out a reasonable number.

This is the behaviour I get with optimizations enabled, with them disabled I get "normal" cout

f() took 471 milliseconds

So is this standard compliant behaviour? Important: it is not that dead code gets optimized away, I can see the lag when running from console, and I can see CPU spike in Task Manager.

greatwolf
  • 20,287
  • 13
  • 71
  • 105
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277

1 Answers1

10

My guess is that this is dead code optimization - and that your load spike is due to the work initializing the vector isn't being optimized away, but the computation of your unused sum variable is.

But when I decide to uncomment the line with couting of the sum then it prints out a reasonable number.

That goes along with my theory, yes - when you're forced to use the result of the computation, the computation itself can't be optimized away.

If you want to confirm that further, make your program say when it's ready and pause for you to press return - that will allow you to wait for any CPU spike to be obviously "gone" before you press return, which will give you more confidence about what's causing it.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Checked, you are right, but now Im confused, if it is smart to figure out that sum isnt used why is it doing the initialization? I guess it cant prove that rand() has no side effects... – NoSenseEtAl Mar 15 '12 at 00:30
  • ouch... ofc it cant prove that rand has no side effects-rand isnt a pure function... it has state. :) but even replacing rand() with i still doesnt prevent initialization... – NoSenseEtAl Mar 15 '12 at 00:32
  • @NoSenseEtAl: Well the initialization does work using `push_back`... so my guess is that even though the compiler may be able to tell that `v` is only used later in ways it can discard, it isn't happy to assume that `push_back()` will have no other side-effects. I wouldn't like to say for sure though. – Jon Skeet Mar 15 '12 at 06:18
  • 1
    `push_back` has its source available to the compiler (`vector` is a template) so that shouldn't be the problem. I presume it's one layer deeper: the memory allocations. – MSalters Mar 15 '12 at 10:41