- #include <stdio.h>
- #include <stdlib.h> /* 包含標(biāo)準(zhǔn)庫頭文件 */
- #include <sys/time.h>
-
- int main(int argc, char **argv)
- {
- struct timeval start,stop,diff;
- gettimeofday(&start,0);
- //做你要做的事...
- gettimeofday(&stop,0);
- timeval_subtract(&diff,&start,&stop);
- printf("總計(jì)用時:%d 微秒\n",diff.tv_usec);
- }
-
- /**
- * 計(jì)算兩個時間的間隔,得到時間差
- * @param struct timeval* resule 返回計(jì)算出來的時間
- * @param struct timeval* x 需要計(jì)算的前一個時間
- * @param struct timeval* y 需要計(jì)算的后一個時間
- * return -1 failure ,0 success
- **/
- int timeval_subtract(struct timeval* result, struct timeval* x, struct timeval* y)
- {
- int nsec;
-
- if ( x->tv_sec>y->tv_sec )
- return -1;
-
- if ( (x->tv_sec==y->tv_sec) && (x->tv_usec>y->tv_usec) )
- return -1;
-
- result->tv_sec = ( y->tv_sec-x->tv_sec );
- result->tv_usec = ( y->tv_usec-x->tv_usec );
-
- if (result->tv_usec<0)
- {
- result->tv_sec -= 1;
- result->tv_usec+=1000000;
- }
-
- return 0;
- }
=========================================================================
- --------------------------------------------------
- #include <sys/time.h>
- #include <unistd.h>
- int gettimeofday(struct timeval *tv,struct timezone *tz);
- 功能:將目前的時間以tv所指的結(jié)構(gòu)返回。
- struct timeval{
- long tv_sec;//秒
- long tv_usec;//微秒
- };
- 將其中的tv_usec轉(zhuǎn)換到毫秒即可。
- timezone結(jié)構(gòu)自己查吧
-
-
-
- 附錄:
- -------------------------------------------------
- Linux下獲得系統(tǒng)時間的C語言的實(shí)現(xiàn)方法
- #include<time.h> //C語言的頭文件
- #include<stdio.h> //C語言的I/O
-
- void main()
- {
- time_t now; //實(shí)例化time_t結(jié)構(gòu)
- struct tm *timenow; //實(shí)例化tm結(jié)構(gòu)指針
- time(&now);
- //time函數(shù)讀取現(xiàn)在的時間(國際標(biāo)準(zhǔn)時間非北京時間),然后傳值給now
-
- timenow = localtime(&now);
- //localtime函數(shù)把從time取得的時間now換算成你電腦中的時間(就是你設(shè)置的地區(qū))
-
- printf("Local time is %s\n",asctime(timenow));
- //上句中asctime函數(shù)把時間轉(zhuǎn)換成字符,通過printf()函數(shù)輸出
- }
-
- 注釋:time_t是一個在time.h中定義好的結(jié)構(gòu)體。而tm結(jié)構(gòu)體的原形如下:
-
- struct tm
- {
- int tm_sec;//seconds 0-61
- int tm_min;//minutes 1-59
- int tm_hour;//hours 0-23
- int tm_mday;//day of the month 1-31
- int tm_mon;//months since jan 0-11
- int tm_year;//years from 1900
- int tm_wday;//days since Sunday, 0-6
- int tm_yday;//days since Jan 1, 0-365
- int tm_isdst;//Daylight Saving time indicator
- };
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點(diǎn)擊舉報。