> 文章列表 > c++获取时间戳的方法总结

c++获取时间戳的方法总结

c++获取时间戳的方法总结

目录

  • 1. 系统时间戳获取方法
    • 1.1 Windows系统获取时间间隔的方式
    • 1.2 Linux系统获取时间间隔的方式
    • 1.3 获取时间戳
  • 2. c++语言获取时间戳

1. 系统级时间戳获取方法

1.1 Windows系统获取时间间隔的方式

API说明
Windows平台下使用 GetLocalTime

VOID GetLocalTime(LPSYSTEMTIME lpSystemTime //address of system times structure
);

参数说明:
• lpSystemTime: 指向一个用户自定义包含日期和时间信息的类型为 SYSTEMTIME 的变量,该变量用来保存函数获取的时间信息。
此函数会把获取的系统时间信息存储到SYSTEMTIME结构体里边

typedef struct _SYSTEMTIME
{WORD wYear;//年WORD wMonth;//月WORD wDayOfWeek;//星期,0为星期日,1为星期一,2为星期二……WORD wDay;//日WORD wHour;//时WORD wMinute;//分WORD wSecond;//秒WORD wMilliseconds;//毫秒
}SYSTEMTIME,*PSYSTEMTIME;

• 使用示例:

SYSTEMTIME stTime;
GetLocalTime(&stTime);
WORD wYear = stTime.wYear;
WORD wMonth = stTime.wMonth;
WORD wDay = stTime.wDay;
WORD wHour = stTime.wHour;
WORD wMinute = stTime.wMinute;
WORD wSecond = stTime.wSecond;
CString m_date;

//m_date字符串即为当前时间。如:2010年4月23日 11:12:45

m_date.Format("%4d年%2d月%2d日 %2d:%2d:%2d", wYear, wMonth, wDay, wHour, wMinute, wSecond);

• 执行结果
在这里插入图片描述

1.2 Linux系统获取时间间隔的方式

linux平台下使用 gettimeofday

#include <sys/time.h>
int gettimeofday(struct timeval*tv, struct timezone *tz);

其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:

struct timezone{int tz_minuteswest;/*格林威治时间往西方的时差*/int tz_dsttime;/*DST 时间的修正方式*/
}

timezone 参数若不使用则传入NULL即可。
而结构体timeval的定义为:

struct timeval{long int tv_sec; // 秒数long int tv_usec; // 微秒数
}

它获得的时间精确到微秒(1e-6 s)量级。在一段代码前后分别使用gettimeofday可以计算代码执行时间:

struct timeval tv_begin, tv_end;
gettimeofday(&tv_begin, NULL);
foo();
gettimeofday(&tv_end, NULL);

函数执行成功后返回0,失败后返回-1,错误代码存于errno中。

1.3 获取时间戳

代码:

#ifdef _WIN32
#include <time.h>
#include <windows.h>
#else
#include <sys/time.h>
#endifusing namespace std;unsigned long long GetCurrentTimeMsec()
{
#ifdef _WIN32struct timeval tv;time_t clock;struct tm tm;SYSTEMTIME wtm;GetLocalTime(&wtm);tm.tm_year = wtm.wYear - 1900;tm.tm_mon = wtm.wMonth - 1;tm.tm_mday = wtm.wDay;tm.tm_hour = wtm.wHour;tm.tm_min = wtm.wMinute;tm.tm_sec = wtm.wSecond;tm.tm_isdst = -1;clock = mktime(&tm);tv.tv_sec = clock;tv.tv_usec = wtm.wMilliseconds * 1000;return ((unsigned long long)tv.tv_sec * 1000 + (unsigned long long)tv.tv_usec / 1000);
#elsestruct timeval tv;gettimeofday(&tv, NULL);return ((unsigned long long)tv.tv_sec * 1000 + (unsigned long long)tv.tv_usec / 1000);
#endif
}

2. c++语言获取时间戳

c++11有一个chrono类可以获取时间戳

#include <chrono>time_t GetCurrentTimeMsec(){auto time = chrono::time_point_cast<chrono::milliseconds>(chrono::system_clock::now());time_t timestamp = time.time_since_epoch().count();return timestamp;
}

参考:https://developer.aliyun.com/article/1171304