先補充一下,精確的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