tshah06
tshah06

Reputation: 2755

Example of C++ 11 std::chrono::duration

I wrote one sample function to understand behavior of std::chrono::duration which recently introduced as part of C++11 standard.

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();
}

Output:

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

When I ran the above function, the program surprisingly waited for 10 seconds after printing 1) rather than after printing 2). I was expecting the program to wait after printing "Waiting for 10 seconds..." then wait and then print "Done." but it printed "100 second is 1 minute." then waited for 10 seconds and then the rest of output.

Upvotes: 3

Views: 14737

Answers (1)

Twig
Twig

Reputation: 611

Does it work correctly if you change

cout<<"Waiting for 10 seconds...";

to

cout<<"Waiting for 10 seconds..." << endl;

It may be that its not flushing, so it doesn't print that line yet.

Upvotes: 9

Related Questions