使用timeval擷取Linux 毫秒級計時

來源:互聯網
上載者:User

先補充一下,精確的sleep用usleep(1000 * seconds
);

今天因為這個函數,又費了很多時間,每次用這個函數,總是會這樣,上網查,精簡代碼,使用,忘記,NND。

今天在cublog上看到一個兄弟的遭遇也是和我一樣的,特此mark。

http://blog.chinaunix.net/u3/93926/showart_1874757.html

原帖內容
-->

這個問題不止遇見了一次了,但是總是懶得記錄下來,所以每次碰到總是要寫個test代碼去測試一下。

問題如下:
在debian
linux的man頁中對gettimeofday函數的說明中,有這樣一個說明:

DESCRIPTION<br /> The functions gettimeofday and settimeofday can get and set the time as<br /> well as a timezone. The tv argument is a timeval struct, as specified<br /> in <sys/time.h>:<br /> struct timeval {<br /> time_t tv_sec; /* seconds */<br /> suseconds_t tv_usec; /* microseconds */<br /> };

其中對tv_usec的說明為時間的毫秒部分。
而在實際中,該函數以及Linux核心返回的timeval
類型的時間值,tv_usec代表的是微秒精度(10的-6次方秒)。

測試代碼如下:
<br />#include <stdio.h><br />#include <sys/time.h><br />#include <time.h><br /> int gettimeofday(struct timeval *tv, struct timezone *tz);</p><p>int main(int argc,char * argv[]){<br /> struct timeval tv;<br /> while(1){<br /> gettimeofday(&tv,NULL);<br /> printf("time %u:%u/n",tv.tv_sec,tv.tv_usec);<br /> sleep(2);<br /> }<br /> return 0;<br />}<br />

返回結果為:

evil@dcenter:~/tmp$ ./a.out<br />time 1142077839:903605<br />time 1142077841:910129<br />time 1142077843:920155<br />time 1142077845:930180<br />time 1142077847:940205<br />time 1142077849:950231<br />time 1142077851:960256<br />time 1142077853:970280<br />time 1142077855:980307<br />time 1142077857:990331 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.