Can compiler reorder code over calls to std::chrono::system_clock::now()?

∥☆過路亽.° 提交于 2020-01-02 03:26:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/9712192/can-compiler-reorder-code-over-calls-to-stdchronosystem-clocknow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!