开发者

c++, sleep, and loops

开发者 https://www.devze.com 2023-01-02 18:51 出处:网络
Ok, this is just out 开发者_开发问答of curiousity, but why does the sleep function NOT work in a loop, or how can I Get it to work in a loop?

Ok, this is just out 开发者_开发问答of curiousity, but why does the sleep function NOT work in a loop, or how can I Get it to work in a loop?

for(int i = 0; i < 5; i++) { 
     cout << i << endl; 
     sleep(2); 
} 


cout is buffered, meaning its contents aren't always written to the console right away. Try adding cout.flush() right before sleep(2);


If that isn't working for you you could try this code:

#include <iostream>
#include <windows.h>

...

for(int i = 0; i < 5; i++) { 
     cout << i << endl; 
     Sleep(2000); 
} 


Have you tried unrolling the loop to see if that behaves the same way?

cout << 1 << endl;
sleep(2);
cout << 2 << endl;
sleep(2);
// Etc.

Assuming that behaves the same way, even though std::endl is supposed to flush the buffer, it really does look like dave.kilian has the right idea that cout isn't getting flushed until the program (presumably) terminates.

In that case, try doing the std::flush and see if that helps - it's possible you have a bug (missed feature?) in your standard library.

Another thing to try is to redirect the output to a file while watching it with tail -f in another window. See if the same delay occurs when redirected.

Finally try playing with the compiler's optimization level and see if that changes the results.


In my humble opinion, this program should work correctly. Maybe your std::cout is redirected somewhere else? You don't call the correct sleep() function (but no header provided)? Or other problem? But it should work.


Dave has already given you the answer, so I won't touch on that. However, if its purely for debugging or prototype code, you could also pipe the output to std::cout's sibling, std::cerr, which is unbuffered to begin with. This means you do not need to call flush explicitly and you do not need to add an endl to your output.


Try Sleep() instead of sleep()

0

精彩评论

暂无评论...
验证码 换一张
取 消