1、获取时间戳
#include <time.h>
time_t
time
(time_t *calptr)
- time返回当前时间的时间戳,也就是从世界时到现在的秒数;
- time_t实际就是一个uint64_t;
- calptr不为空时,时间戳也会写入到该指针中;
示例:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
time_t curTime;
curTime =
time
(NULL);
printf("curTime = %ld\n",curTime );
return
0;
}
2、
gettimeofday()和clock_gettime()
time函数只能得到秒精度的时间,为了获得更高精度的时间戳,需要其他函数。gettimeofday函数可以获得微秒精度的时间戳,用结构体timeval来保存;clock_gettime函数可以获得纳秒精度的时间戳,用结构体timespec来保存。
#include <sys/time.h>
int gettimeofday(struct timeval *tp, void *tzp);
int clock_gettime(clockid_t clock_id, strcut timespec *tsp);
clock_id有多个选择,当选择为CLOCK_REALTIME时与
time
的功能相似,但是时间精度更高。
两个函数的结构体定义如下:
struct timeval
{
long tv_sec; /*秒*/
long tv_usec; /*微秒*/
};
struct timespec
{
time_t tv_sec;
//
秒
long tv_nsec;
//
纳秒
};
示例:
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int main(int argc,char *argv[])
{
time_t dwCurTime1;
dwCurTime1 = time(NULL);
struct timeval stCurTime2;
gettimeofday(&stCurTime2, NULL);
struct timespec stCurTime3;
clock_gettime(CLOCK_REALTIME, &stCurTime3);
printf("Time1:%ds\n",dwCurTime1);
printf("Time2:%ds---%ldus\n",stCurTime2.tv_sec,stCurTime2.tv_usec);
printf("Time3:%ds---%ldns\n",stCurTime3.tv_sec,stCurTime3.tv_nsec);
return 0;
}
/*****************************************************************************************************/
*
*秒,毫秒,微秒,纳秒实现接口
*
/*****************************************************************************************************/
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include "fileproperty.h"
//秒
u64 GetSec()
{
time_t sectime;
sectime = time(NULL);
//printf("sectime:%ds\n",sectime);
return sectime;
}
//毫秒
u64 GetMsec()
{
long msec = 0;
struct timeval msectime;
gettimeofday(&msectime, NULL);
msec =msectime.tv_sec * 1000 + msectime.tv_usec / 1000;
//printf("msectime:%ldms\n",msec);
return msec;
}
//微秒
u64 GetUsec()
{
long usec = 0;
struct timeval usectime;
gettimeofday(&usectime, NULL);
usec = usectime.tv_sec * 1000000 + usectime.tv_usec;
//printf("usectime:%dus\n",usec);
return usec;
}
//纳秒
u64 GetNsec()
{
long nsec = 0;
struct timespec nsectime;
clock_gettime(CLOCK_REALTIME, &nsectime);
nsec = nsectime.tv_sec * 1000000000 + nsectime.tv_nsec;
//printf("nsectime:%ldns\n",nsec);
return nsec;
}