C++ 获取UTC时间精确到微妙

在日常开发过程中经常会使用到时间类函数的统计,其中获取1970年至今的UTC时间是比较常使用的,但是在windows下没有直接能够精确到微妙级的函数可用。本文提供方法正好可以解决这类需求问题。

 

注意1:

time 函数有两中用法,如果他里面带参数,那就把返回值放在参数里面,否则就直接返回time值,在unix中是国际标准时间公元1 9 7 0年1月1日0 0 : 0 0 : 0 0以来经过的秒数。这种秒数是以数据类型t i m e t表示的,可以用%ld打印出来


注意2:

GetTickCount,函数。GetTickCount返回(retrieve)从操作系统启动到现在所经过(elapsed)的毫秒数,它的返回值是DWORD。





下面先给出C++实现代码

#ifndef UTC_TIME_STAMP_H_

#define UTC_TIME_STAMP_H_
 
#include <windows.h>
#include <sys/timeb.h>
#include <time.h>
 
#if !defined(_WINSOCK2API_) && !defined(_WINSOCKAPI_)
struct timeval
{
long tv_sec;
long tv_usec;
};
#endif
 
static int gettimeofday(struct timeval* tv)
{
    union {
             long long ns100;
             FILETIME ft;
    } now;
    GetSystemTimeAsFileTime (&now.ft);
    tv->tv_usec = (long) ((now.ns100 / 10LL) % 1000000LL);
    tv->tv_sec = (long) ((now.ns100 - 116444736000000000LL) / 10000000LL);
 
    return (0);
}

//获取1970年至今UTC的微妙数
static time_t TimeConversion::GetUtcCaressing()
{
    timeval tv;
    gettimeofday(&tv); 
    return ((time_t)tv.tv_sec*(time_t)1000000+tv.tv_usec);
}
#endif
 
 
接下来给出使用方法:

timeval tv;
gettimeofday(&tv);
  

或者直接调用:GetUtcCaressing();

 

最后说明:本文代码在vs2008与VS2010下都进行了测试,可放心使用


原文地址:https://www.cnblogs.com/hzcya1995/p/13318468.html