Sleep () delays my program too early. What am I doing wrong?

I want to write a small program that should print something like

CPU testing ... done
RAM testing ... done

etc.

I wrote the following program in C:

printf( "testing RAM...\t\t" ); sleep( sleep_time ); printf( "done\n\n" ); printf( "testing HDD...\t\t" ); sleep( sleep_time ); printf( "done\n\n" ); 

where sleep_time is 2.

However, instead of first typing β€œCPU testing ...”, then waiting, and then typing β€œdone,” it first waits and then prints the entire line, which is not quite what I had in mind.

I believe this is due to automatic compiler optimization.
Anyway, what can I do to get the desired result?

I am using Xcode 3.1 in OSX 10.5.6

Thanks,
Bastian

+4
source share
3 answers

The problem is that your prints are buffered. just before bedtime, call fflush (stdout); to flush the buffer

+21
source

the compiler cannot reorder and sleep, as they are the "externally observable behavior" of the abstract C machine.

What you get is related to stdout buffering. You can use fflush or print for stderr, which is not buffered.

+2
source

Just using \ n or endl at the end of the first printf should be enough

0
source

All Articles