sleep()过早地拖延我的程序。我究竟做错了什么?

时间:2021-06-19 00:05:50

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

我想写一个应该打印的小程序

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

测试CPU ...完成测试RAM ...完成

and so on.

等等。

I wrote the following program in C:

我用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.

sleep_time是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.

然而,不是首先打印“测试CPU ...”,然后等待,然后打印“完成”,它首先等待,然后打印整行,这不是我想到的。

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

我在OSX 10.5.6上使用XCode 3.1

Thank you,
Bastian

谢谢巴斯蒂安

3 个解决方案

#1


21  

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

问题是您的打印是缓冲的。在睡觉前,请拨打fflush(stdout);刷新缓冲区

#2


2  

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

编译器无法重新排序打印和睡眠,因为它们是C抽象机器的“外部可观察行为”。

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

你得到的是由于stdout缓冲。您可以使用fflush或打印到未缓冲的stderr。

#3


0  

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

只需在第一个printf末尾使用\ n或endl即可

#1


21  

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

问题是您的打印是缓冲的。在睡觉前,请拨打fflush(stdout);刷新缓冲区

#2


2  

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

编译器无法重新排序打印和睡眠,因为它们是C抽象机器的“外部可观察行为”。

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

你得到的是由于stdout缓冲。您可以使用fflush或打印到未缓冲的stderr。

#3


0  

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

只需在第一个printf末尾使用\ n或endl即可