阅 读 文 章

在C程式中要怎么用 sleep() 才能够sleep小于一秒?

[来源:网上转载 (http://www.chinaunix.net) | 作者:网友(不详) | 时间:2007-07-07 | 浏览:人次 ]

  首先要注意的是,你只能指定 delay 的「最短」时间;实际上会 delay 多久和 
  系统的 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

最新评论 共有0位网友发表了评论

发表评论

评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名:(注册)
密码:
验证码:
匿名发表

网站地图友情连接交流论坛网站投稿广告服务联系我们留言本站长统计
Some rights reserved: www.chmhome.com, 鄂ICP备07010232号 E-mail:chinakafei@live.com,QQ:552766
中国咖啡技术网(Chmhome):国外编程技术书籍,中文编程手册,经典编程文章,交流技术,技术软件下载,计算机论文,毕业论文.