Linux下的usleep函数

Linux大全评论4.9K views阅读模式

Linux中用的是时间片轮转算法,进程轮训要消耗时间,转换到一个进程来执行要消耗时间。结果在进程睡眠和运行过程中,许多时间已经过去了。

sleep()是以秒为单位的,要想延迟一个较小的时间,就需要用到usleep()。

另外还有个nanosleep(),用法好像很复杂。

usleep可能很难保证时间精度。我写了一段测试代码

  1. #include <stdio.h>   
  2. #include <unistd.h>   
  3. #include <sys/time.h>   
  4.   
  5. int main(void)  
  6. {  
  7.     int i;  
  8.     struct timeval tvTotal;  
  9.     struct timeval tvBegin, tvEnd, tvSub;  
  10.   
  11.     tvTotal.tv_sec = 0;  
  12.     tvTotal.tv_usec = 0;  
  13.     for (i = 0; i < 100; i++)   
  14.     {  
  15.         gettimeofday(&tvBegin, NULL);  
  16.         usleep(1000);     // 1000 us(microsecond/微秒) = 1 ms(毫秒)    
  17.         gettimeofday(&tvEnd, NULL);  
  18.         timersub(&tvEnd, &tvBegin, &tvSub);  
  19.         tvTotal.tv_sec += tvSub.tv_sec;  
  20.         tvTotal.tv_usec += tvSub.tv_usec;  
  21.         printf("%d\n", tvSub.tv_usec);  
  22.     }  
  23.     printf("try to usleep 1000 us 100 times, average of result is: %ld\n", tvTotal.tv_sec*1000*10+tvTotal.tv_usec/100);  
  24.     return   0;  
  25. }  

企鹅博客
  • 本文由 发表于 2020年5月15日 11:37:37
  • 转载请务必保留本文链接:https://www.qieseo.com/171681.html

发表评论