C++中获取UTC时间精确到微秒的实现代码

2016-02-19 08:55 129 1 收藏

下面请跟着图老师小编一起来了解下C++中获取UTC时间精确到微秒的实现代码,精心挑选的内容希望大家喜欢,不要忘记点个赞哦!

【 tulaoshi.com - 编程语言 】

在日常开发过程中经常会使用到时间类函数的统计,其中获取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("%dn",timep);

来源:http://www.tulaoshi.com/n/20160219/1588809.html

延伸阅读
标签: Web开发
这个问题在某些时候微不足道,甚至可以忽略,但有些时候,这个问题就非常严重,它很可能让我们的程序得不到预期的结果。因此我们需要解决这个问题。 如果你读过 MSDN,你会发现并非所有插入到 innerHTML 中的脚本都不能执行,如果这段脚本的 script 标签中包含了 defer 属性,IE 会正确的执行这些脚本程序。但不幸的是,Moziila/Firefox 和 O...
标签: Web开发
代码如下: script language="javascript" /*Javascript中暂停功能的实现 Javascript本身没有暂停功能(sleep不能使用)同时 vbscript也不能使用doEvents,故编写此函数实现此功能。 javascript作为弱对象语言,一个函数也可以作为一个对象使用。 比如: function Test(){  alert("hellow");  this.NextStep=f...
  ANSI C++ 中的 Singleton 实现说难不难,说轻易也不轻易,很多人写 ANSI C++ 的 Singleton class 都有错误。这篇文章讨论怎样在 ANSI c++ 中写 Singleton class, 希望对大家有帮助。   《设计模式》中把 Singleton 写成返回指针: class Singleton{ public:     static Singleton* Instance(...
标签: Web开发
代码如下: /* * Copyright (c) 2010 刘建华 * * The above copyright notice shall be * included in all copies or substantial portions of the Software. * Example: divdemo/div divdemo/div script type="text/javascript" var o = $(document); o.mousemove( function(e){ var d = document.getElementById("demo"); d.s...
代码如下所示: 代码如下: #include stdio.h int main() {  // 主要是找到行和列的关系    int i,j,k;      for(i=0;i4;i++)  //做为行循环    {     for(j=0;j=2-i;j++)  // 打印一行中的空白      printf(" ");     for(k=...

经验教程

794

收藏

45
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部