前言:
在開發中,很多時候需要知道各個函數或者是某些設備對命令的操作用時,因此需要用到 gettimeofday 來獲取當前時鐘。
一,函數說明
#include
int gettimeofday(struct timeval *tv, struct timezone *tz);
注意:
點擊(此處)折疊或打開
struct timeval
{
long int tv_sec; // 秒數
long int tv_usec; // 微秒數
}
它獲得的時間精確到微秒(1e-6 s)量級點擊(此處)折疊或打開
struct timezone
{
int tz_minuteswest;/*格林威治時間往西方的時差*/
int tz_dsttime; /*DST 時間的修正方式*/
}
timezone 參數若不使用則傳入NULL即可。點擊(此處)折疊或打開
DST_NONE /*不使用*/
DST_USA /*美國*/
DST_AUST /*澳洲*/
DST_WET /*西歐*/
DST_MET /*中歐*/
DST_EET /*東歐*/
DST_CAN /*加拿大*/
DST_GB /*大不列顛*/
DST_RUM /*羅馬尼亞*/
DST_TUR /*土耳其*/
DST_AUSTALT /*澳洲(1986年以後)*/
返回值點擊(此處)折疊或打開
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <sys/time.h>
5 int time_substract(struct timeval *result, struct timeval *begin,struct timeval *end)
6 {
7 if(begin->tv_sec > end->tv_sec) return -1;
8 if((begin->tv_sec == end->tv_sec) && (begin->tv_usec > end->tv_usec)) return -2;
9 result->tv_sec = (end->tv_sec - begin->tv_sec);
10 result->tv_usec = (end->tv_usec - begin->tv_usec);
11
12 if(result->tv_usec < 0)
13 {
14 result->tv_sec--;
15 result->tv_usec += 1000000;
16 }
17 return 0;
18 }
19 int main(int argc, char **argv)
20 {
21 struct timeval start,stop,diff;
22 memset(&start,0,sizeof(struct timeval));
23 memset(&stop,0,sizeof(struct timeval));
24 memset(&diff,0,sizeof(struct timeval));
25 gettimeofday(&start,0);
26 //做你要做的事...
27 printf("hello world\n");
28 gettimeofday(&stop,0);
29 time_substract(&diff,&start,&stop);
30 printf("Total time : %d s,%d us\n",(int)diff.tv_sec,(int)diff.tv_usec);
31 }
操作結果:
轉載自:http://blog.chinaunix.net/uid-28458801-id-4214306.html