获取当前的时间的秒数和微秒数本方法需要用到gettimeofday()
函数,该函数需要引入的头文件是sys/time.h
。
// sys/time.hstruct timeval{long tv_sec; //秒 long tv_usec; //微秒 }; struct timezone {int tz_minuteswest; //格林威治时间往西方的时差,即和格林威治差了多少分钟 int tz_dsttime;//DST 时间的修正方式}; /*** @params struct timeval* @params struct timezone* @return 成功时返回0,失败时返回-1 */int gettimeofday (struct timeval * tv, struct timezone * tz);
#include <stdlib.h>#include <stdio.h>#include <sys/time.h>#include <unistd.h>int main(){struct timeval tv;gettimeofday(&tv,NULL);printf("second:%ld\n",tv.tv_sec);//秒printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒sleep(3); printf("3s later:");gettimeofday(&tv,NULL);printf("second:%ld\n",tv.tv_sec);//秒printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒return 0;}
参考文献:
/li_wen01/article/details/80422340