Linux下的usleep函数


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. }  

在虚拟机上运行的结果,证实偏差很大:
[root@localhost ~]# ./test
1118
1700
1855
3428
2148
3097
1347
1339
1800
1837
4322
4228
8866
1343
1902
1816
2353
1238
2065
1347
1775
1717
1924
2142
3011
1945
3078
6542
1918
2647
1780
2507
2447
4542
3574
8839
2014
1503
1240
1844
1993
1903
1936
1498
1798
1357
2882
7804
1234
1323
2404
1410
1972
1909
2066
1901
1371
2113
1477
1477
1403
6248
1691
2539
2005
1303
1940
1975
1983
2167
2021
1484
1460
2364
5229
1890
1193
2132
1894
1876
1973
2120
1844
1949
1407
1727
2186
1872
1900
7160
1703
1971
1243
1495
1861
2017
1223
1125
1733
1498
try to usleep 1000 us 100 times, average of result is: 2327

抖动非常厉害。
明天找个arm板在测测看看。

相关内容