2
我寫了一個示例函數來了解std::chrono::duration
最近作爲C++ 11標準的一部分引入的行爲。C++示例11 std :: chrono :: duration
void exampleForDuration()
{
seconds Sec(minutes(1));
cout<<"1 second is "<<duration_cast<nanoseconds>(seconds(1)).count()<<" nanoseconds"<<endl;
cout<<"1 minute is "<<Sec.count()<<" seconds"<<endl;
cout<<"1 second is "<<duration_cast<duration<int,centi>>(seconds(1)).count()<<" centiseconds"<<endl;
cout<<"100 second is "<<duration_cast<minutes>(seconds(100)).count()<<" minute."<<endl;
cout<<"Waiting for 10 seconds...";
auto start=system_clock::now();
this_thread::sleep_for(seconds(10));
cout<<"Done."<<endl;
auto end=system_clock::now();
auto waitedFor=end-start;
cout<<"Waited for "<<duration_cast<seconds>(waitedFor).count()<<" seconds"<<endl;
printCurrentDateTime();
}
輸出:
1 second is 1000000000 nanoseconds 1 minute is 60 seconds 1 second is 100 centiseconds 100 second is 1 minute. -------> 1) Waiting for 10 seconds...Done. -------> 2) Waited for 10 seconds
當我跑的上述功能,該程序等待出奇10秒鐘打印1之後),而不是打印2之後)。我打算在打印完成後等待程序等待10秒...然後等待,然後打印「完成」。但它打印「100秒是1分鐘」。然後等待10秒鐘,然後輸出其餘部分。
對我來說可以修復它 – Twig
是的,它在添加endl後起作用。是的,似乎問題是由於流失。我刪除了endl並嘗試cout.flush(),它的工作方式與我的預期完全一致。非常感謝答覆。 – tshah06
@ user1612089作爲一個方面說明,這不僅僅是一個答覆,它是一個答案,[接受](http://meta.stackexchange.com/q/5234/162011)是正確答案的正確答案。 –