最近在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:
#include <stdio.h>#include <time.h>#include <windows.h>int main(){printf("The start clock is: %ld\n", clock());Sleep(2000);printf("The end clock is: %ld\n", clock());return 0;}
Linux:
#include <stdio.h>#include <time.h>#include <unistd.h>int main(){ printf("The start clock is: %ld\n", clock()); sleep(2); printf("The end clock is: %ld\n", clock()); return 0;}
啟動並執行結果:
Windows:
The start clock is: 1The end clock is: 2001
Linux:
The start clock is: 0The end clock is: 0
這說明在Windows Sleep()佔用processor time,Linux下的sleep()不佔用processor time,這可能與底層的sleep()實現機制的不同所導致的。