首页 > 编程知识 正文

linux设置系统时间精确到毫秒,linux显示毫秒时间

时间:2023-05-04 04:09:20 阅读:241973 作者:4826

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 = %ldn",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:%dsn",dwCurTime1);
    printf("Time2:%ds---%ldusn",stCurTime2.tv_sec,stCurTime2.tv_usec);
    printf("Time3:%ds---%ldnsn",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:%dsn",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:%ldmsn",msec);
    return msec;
}
//微秒
u64 GetUsec()
{
    long usec = 0;
    struct timeval usectime;
    gettimeofday(&usectime, NULL);
    usec = usectime.tv_sec * 1000000 + usectime.tv_usec;
    
    //printf("usectime:%dusn",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:%ldnsn",nsec);
    return nsec;
}

 

 

 

 

 

 

 

 

 

 

 

 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。