读书人

which way may I use for implement a

发布时间: 2012-03-26 15:46:56 作者: rapoo

which way may I use for implement a delay?
frist :

use a do-nothing loop like
for(i=0;i <1000000;i++)
{ /* do nothing */}

second:


use standard library functiom clock
now = clock();
while (clock() - now < 1 )
{ /* do nothing */ }


which one is better??


regards
securi_c

[解决办法]
E文啊。
Both can implement a delay. But the problem about the first approach is that you won 't how many seconds it delays. Maybe you should use system APIs, such as sleep(), etc to give away cpu when your program are blocked.

[解决办法]
The two methods you mentioned are both do-nothing way, and the second one is more accurate than the first one. The flaw of do-nothing way is that your process takes much cpu time in the loop, even though they can be scheduled to other processes to increase the system throughput.

Better way to implement a delay in your own program is to use os APIs. In windows, you can use Sleep to suspend your process for some milliseconds specified by the parameter
[解决办法]
if you have some knowledge of the design and implementation of operating system, it is trivial for you to answer your own questions. you should have it in your mind that os can schedule any processes in waiting-queue, based on schedule algorithm. sleep() can prevent your process from running for specified interval, but can not make sure your process will wake in just 1 second

读书人网 >C++

热点推荐