linux 不能用clock 计算sleep的时间

 

http://bbs.csdn.net/topics/390558707

 

在Windows Sleep()占用processor time,Linux下的sleep()不占用processor time,这可能与底层的sleep()实现机制的不同所导致的。

 

clock(), sleep(), Sleep()在windows和Linux的区别

 

最近在ARM上的Linux进行开发,需要将Windows下编写的C程序移植到Linux上去,其中需要将底层的SPI驱动实现,以及上层的Socket通信改写,其中应用程序也需要改变一些,整个过程中,让程序顺利跑起来没花费大的力气,这里要感谢强大的Eclipse +ARM-linux-gcc组合,但是在调试过程中,发现很多有趣的问题,其中一个就是关于Windows下的Sleep()函数和Linux下的sleep()函数的区别。

在windows下的Sleep()函数需要包含windows.h头文件,而在Linux下需要包含的头文件是unistd.h头文件,说明sleep()函数不是标准的C语言库,而且在Windows下Sleep()睡眠时间为毫秒,而Linux下的sleep()函数时间为秒,如果需要实现更精确的时间,Linux下可以采用usleep()函数,微妙级别,在Windows下貌似没有更精确的,只能到毫秒级别(个人观点,还没证实)。说到这,其实windows和Linux的区别其实还是非常小,和clock()函数组合后,发现了其中的不同,其中clock()函数是标准的C语言库提供的函数,功能如下:

clock returns the processor time used by program since the beginning of the execution, or -1 if unavailable. clock() / CLOCKS_PER_SEC is a time in seconds.

这里提到clock()函数返回的程序运行过程耗掉得process time,也就是CPU time,在windows下和Linux下,我们分别测试如下代码:

Windows:

 

[cpp] view plaincopy
 
  1. #include <stdio.h>  
  2. #include <time.h>  
  3. #include <windows.h>  
  4.   
  5. int main()  
  6. {  
  7.     printf("The start clock is: %ld\n", clock());  
  8.     Sleep(2000);  
  9.     printf("The end clock is: %ld\n", clock());  
  10.   
  11.     return 0;  
  12. }  

Linux:

 

 

[cpp] view plaincopy
 
  1. #include <stdio.h>  
  2. #include <time.h>  
  3. #include <unistd.h>  
  4.   
  5. int main()  
  6. {  
  7.         printf("The start clock is: %ld\n", clock());  
  8.         sleep(2);  
  9.         printf("The end clock is: %ld\n", clock());  
  10.   
  11.         return 0;  
  12. }  


运行的结果:

 

Windows:

 

[cpp] view plaincopy
 
  1. The start clock is: 1  
  2. The end clock is: 2001  


Linux:

 

 

[cpp] view plaincopy
 
  1. The start clock is: 0  
  2. The end clock is: 0  


这说明在Windows Sleep()占用processor time,Linux下的sleep()不占用processor time,这可能与底层的sleep()实现机制的不同所导致的。

 

 

posted on 2015-05-13 08:49  okgogo2000  阅读(1276)  评论(0编辑  收藏  举报