3

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.

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, It worked after adding endl. Yes it seems that the problem is due to flusing. I removed endl and tried cout.flush() and it worked exactly the way i expected. Thanks a lot for the reply.
@user1612089 As a side note, this is not only a mere reply, it's an answer and accepting is the correct way to respond to correct answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.