获取当前的时间的秒数和微秒数本方法须要用到gettimeofday()函数,该函数须要引入的头文件是 sys/time.h 。ios
函数说明int gettimeofday (struct timeval * tv, struct timezone * tz)app
一、返回值:该函数成功时返回0,失败时返回-1
二、参数
struct timeval{
long tv_sec; //秒
long tv_usec; //微秒
};
struct timezone
{
int tz_minuteswest; //和Greenwich 时间差了多少分钟
int tz_dsttime; //日光节约时间的状态
函数
}; .net
3.实例code
#include<iostream> #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); // 为方便观看,让程序睡三秒后对比 std::cout << "3s later:" << std::endl; 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; }
结果:blog
second:1467523986
millisecond:1467523986800
microsecond:1467523986800434
3s later:
second:1467523989
millisecond:1467523989800
microsecond:1467523989800697get
四、附
一秒等于1000毫秒
一秒等于1000000微秒
io
一秒等于1000000000纳秒class
文章转载自:https://blog.csdn.net/deyuzhi/article/details/51814934 stream