clock(), sleep(), Sleep()在windows和Linux的區別

來源:互聯網
上載者:User

最近在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()實現機制的不同所導致的。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.