Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

关键词

C++ 时间处理 获取当前时间戳 跨平台 支持秒/微秒/毫秒

Unix-Like 系统的实现

1
2
3
4
5
6
7
8
9
// for Unix-like system
#include <sys/time.h>

uint64_t timestamp_us()
{
struct timeval t;
gettimeofday(&t, 0);
return (uint64_t)(t.tv_sec * 1000000ULL + t.tv_usec);
}

跨平台的实现

基于C++11的std::chrono库实现,支持秒/微秒/毫秒。

timeutil.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <cstdint>

/**
* @brief Time unit enum.
*
*/
enum class timeunit
{
/** second */
s,
/** millisecond */
ms,
/** microsecond */
us,
};

/**
* @brief Get current timestamp.
*
* @param unit time unit
* @return uint64_t timestamp
*/
uint64_t timestamp(timeunit unit);

timeutil.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "timeutil.h"
#include <chrono>

uint64_t timestamp(timeunit unit)
{
// for C++11 and later
auto now = std::chrono::system_clock::now();
auto timestamp_ms = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count();
auto us = static_cast<uint64_t>(timestamp_ms);
uint64_t t = 0;
switch (unit)
{
case timeunit::s:
t = us2s(us);
break;
case timeunit::ms:
t = us2ms(us);
break;
case timeunit::us:
t = us;
break;
default:
break;
}
return t;
}

测试代码

1
2
3
4
5
6
7
8
9
10
11
#include "timeutil.h"
#include "common.hpp"

void TestTimestamp()
{
PrintSubTitle("TestTimestamp");

std::cout << "current timestamp( s): " << cutl::timestamp(cutl::timeunit::s) << std::endl;
std::cout << "current timestamp(ms): " << cutl::timestamp(cutl::timeunit::ms) << std::endl;
std::cout << "current timestamp(us): " << cutl::timestamp(cutl::timeunit::us) << std::endl;
}

运行结果

1
2
3
4
-------------------------------------------TestTimestamp--------------------------------------------
current timestamp( s): 1716129274
current timestamp(ms): 1716129274848
current timestamp(us): 1716129274848863

源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

推荐阅读
C++时间处理2-获取系统开机到现在的运行时间 C++时间处理2-获取系统开机到现在的运行时间 C++时间处理3-格式化时间戳 C++时间处理3-格式化时间戳 C++数据格式化4 - 格式化时间戳 C++数据格式化4 - 格式化时间戳

评论