系统的 scheduling 方式有关,例如系统当时有负载。如果你倒楣的话,它还可
能会 delay 蛮长的时间。
并没有一个标准函式能够在「小睡」(很短的 sleep)期间提供你计数的功能。
某些系统有提供 usleep(n) 的函式,它能够暂停执行 n 微秒(microsecond)
的时间。如果你所使用的系统没有提供 usleep() 函式,那么以下有可在 BSD,
System V 使用中的作法。
接下来的这段程式码是 Doug Gwyn 在 System V 中模拟 4BSD 并利用 4BSD
中的 select() 系统呼叫。Doung 自己都叫它为 'nap()' ;你也可以把它叫做
"usleep()";
/*
usleep -- support routine for 4.2BSD system call emulations
last edit: 29-Oct-1984 D A Gwyn
*/
extern int select();
int
usleep( usec ) /* returns 0 if ok, else -1 */
long usec; /* delay in microseconds */
{
static struct /* `timeval' */
{
long tv_sec; /* seconds */
long tv_usec; /* microsecs */
} delay; /* _select() timeout */
delay.tv_sec = usec / 1000000L;
delay.tv_usec = usec % 1000000L;
return select( 0, (long *)0, (long *)0, (long *)0, &delay );
}
On System V you might do it this way:
/*
subseconds sleeps for System V - or anything that has poll()
Don Libes, 4/1/1991
The BSD analog to this function is defined in terms of
microseconds while poll() is defined in terms of milliseconds.
For compatibility, this function provides accuracy "over the long
run" by truncating actual requests to milliseconds and
accumulating microseconds across calls with the idea that you are
probably calling it in a tight loop, and that over the long run,
the error will even out.
If you aren't calling it in a tight loop, then you almost
certainly aren't making microsecond-resolution requests anyway,
in which case you don't care about microseconds. And if you did,
you wouldn't be using UNIX anyway because random system
indigestion (i.e., scheduling) can make mincemeat out of any
timing code.
Returns 0 if successful timeout, -1 if unsuccessful.
*/
#include <poll.h>
int
usleep(usec)
unsigned int usec; /* microseconds */
| 论坛热门帖子: | [lch203] 写得蛮好的linux学习笔记(10-21) [黑马制造] 学习java的30个目标(10-19) [笑傲股林] 做测试半年了,有点迷茫,应该再学些什么提高自己的测试水平和测试能力呢?(10-19) [udp8589] 大家用google的来吱一声? 用百度的~~也来报道下?(10-18) [沂偌掳兆] 本人总结的一些认为C++比较经典的书籍,希望对大家有用(10-18) |
| TAG标签: | 小于 能够 怎么 long you usec if delay usleep in the |
注册
个人空间
