使用C語言編寫程序需要獲得當前精確時間(1970年1月1日到現(xiàn)在的時間),或者為執(zhí)行計時,可以使用gettimeofday()函數(shù)。
函數(shù)原型:
int gettimeofday(struct timeval*tv, struct timezone *tz);
所需頭文件:
#include <sys/time.h>
說明:
- struct timezone{
- int tz_minuteswest;/*格林威治時間往西方的時差*/
- int tz_dsttime;/*DST 時間的修正方式*/
- }
- struct timeval{
- long int tv_sec; // 秒數(shù)
- long int tv_usec; // 微秒數(shù)
- }
- struct timeval tv_begin, tv_end;
- gettimeofday(&tv_begin, NULL);
- foo();
- gettimeofday(&tv_end, NULL);
實例:
- #include <sys/time.h>
- #include <stdio.h>
- #include <unistd.h>
- int main(void) {
- struct timeval tv;
- gettimeofday(&tv, NULL);
- printf(" tv_usec = %ld tv_sec = %ld\n", tv.tv_usec, tv.tv_sec);
- for(int i = 0; i < 4; i++){
- gettimeofday(&tv, NULL);
- printf("%d) tv_usec = %ld tv_sec = %ld\n", i, tv.tv_usec, tv.tv_sec);
- sleep(1);
- }
- return 0;
- }
運行結(jié)果: