C++中获取UTC时间精确到微秒的实现代码
更新时间:2013年05月16日 16:31:20 作者:
本篇文章是对C++中获取UTC时间精确到微秒的实现进行了详细的分析介绍,需要的朋友参考下
在日常开发过程中经常会使用到时间类函数的统计,其中获取1970年至今的UTC时间是比较常使用的,但是在windows下没有直接能够精确到微妙级的函数可用。本文提供方法正好可以解决这类需求问题。
下面先给出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下都进行了测试,可放心使用
附录:本文同时给出UTC时间秒级UTC获取方法代码:
time_t timep;
struct tm *p;
time(&timep);
p=localtime(&timep);
timep = mktime(p);
printf("%d\n",timep);
下面先给出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下都进行了测试,可放心使用
附录:本文同时给出UTC时间秒级UTC获取方法代码:
复制代码 代码如下:
time_t timep;
struct tm *p;
time(&timep);
p=localtime(&timep);
timep = mktime(p);
printf("%d\n",timep);
相关文章
关于读取popen输出结果时未截断字符串导致的命令行注入详解
这篇文章主要给大家介绍了关于读取popen输出结果时未截断字符串导致的命令行注入的相关资料,文中通过图文及示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。2018-03-03
C++详解使用floor&ceil&round实现保留小数点后两位
这篇文章主要介绍了C++使用floor&ceil&round实现保留小数点后两位的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-07-07


最新评论