views:

316

answers:

3

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

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

and so on.

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 printing "testing CPU..." first, then waiting, then printing "done", it first waits, then prints the whole line, which is not exactly what I had in mind.

I suppose this has something to do with automatic optimization by the compiler.
Anyway, what can I do to get the desired output?

I am using XCode 3.1 on OSX 10.5.6

Thank you,
Bastian

+21  A: 

The issue is that your printings are buffered. immediately before sleeping, call fflush(stdout); to flush the buffer

Johannes Schaub - litb
This is a frequent thing. I've helped tons of people with the c++ version of this problem discover cout.flush() or endl, also.
Greg D
Thank you, this completely solved the problem! Amazing!
BastiBechtold
+2  A: 

compiler can not reorder prints and sleeps, for they are "externally observable behavior" of the C abstract machine.

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

n-alexander
A: 

Just using \n or an endl at the end of the first printf should suffice

Aditya Sehgal