C/C++获取时间戳

我们在开发项目中经常需要使用到时间戳,指Unix时间戳是,是从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒。以下展示了c/c++常用的获取时间戳的方法。

一、C获取时间戳

1、秒

#include<time.h>

time_t result = time(NULL);
printf("time:%lldn",result);

2、毫秒

#include<Windows.h>

SYSTEMTIME tv;
GetLocalTime(&tv);
printf("The local time is %d:%d:%d:%dn", tv.wHour,tv.wMinute,tv.wSecond,tv.wMilliseconds);

3、微秒

#include<time.h>
#include<Windows.h>

struct timevall
{
    long tv_sec;
    long tv_usec;
};

static int gettimeofday(struct timevall* tv)
{
    union {
        long long ns;
        FILETIME ft;
    } now;
    GetSystemTimeAsFileTime(&now.ft);
    tv->tv_usec = (long)((now.ns / 10LL) % 1000000LL);
    tv->tv_sec = (long)((now.ns - 116444736000000000LL) / 10000000LL);
    return (0);
}
void main()
{
  timevall tv;
    gettimeofday(&tv);
    printf("getEventMessage begin.time:%lldn", (time_t)tv.tv_sec * (time_t)1000000 +   tv.tv_usec);
}

二、C++获取时间戳

c++可以直接使用标准库中的接口函数,可以修改std::chrono::microseconds等级,获取对应级别的时间戳。例如:std::chrono::microseconds微秒级。

#include<chrono>

std::cout << std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count() << std::endl;

Linux下一般使用库函数gettimeofday()

#include <sys/time.h>

gettimeofday(&tv,NULL);
printf("millisecond:%ldnn",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>