linux时间的一些函数总结

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;
}

3、秒,毫秒,微秒,纳秒实现接口

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include "fileproperty.h"

//秒
u64 GetSec()
{
    time_t sectime;
    sectime = time(NULL);
    //printf("sectime:%d s\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:%ld ms\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:%d us\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:%ld ns\n",nsec);
    return nsec;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值