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

1. 关键词

C++ 时间处理 系统开机到现在的运行时间 跨平台 支持秒/微秒/毫秒

2. Unix-Like 系统的实现

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

uint64_t clocktime_us()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000ULL + ts.tv_nsec / kThousand;
}

3. 跨平台的实现

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

3.1. 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 clock time for monotone increment time.
*
* @param unit time unit
* @return uint64_t clock time
*/
uint64_t clocktime(timeunit unit);

3.2. 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
27
#include "timeutil.h"
#include <chrono>

uint64_t clocktime(timeunit unit)
{
// for C++11 and later
auto run_time = std::chrono::steady_clock::now();
auto run_time_duration = std::chrono::duration_cast<std::chrono::microseconds>(run_time.time_since_epoch()).count();
auto us = static_cast<uint64_t>(run_time_duration);

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;
}

3.3. 测试代码

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

void TestClocktime()
{
PrintSubTitle("TestClocktime");

auto s = cutl::clocktime(cutl::timeunit::s);
auto ms = cutl::clocktime(cutl::timeunit::ms);
auto us = cutl::clocktime(cutl::timeunit::us);
std::cout << "duration time from system start( s): " << s << std::endl;
std::cout << "duration time from system start(ms): " << ms << std::endl;
std::cout << "duration time from system start(us): " << us << std::endl;
}

3.4. 运行结果

1
2
3
4
-------------------------------------------TestClocktime--------------------------------------------
duration time from system start( s): 1763153
duration time from system start(ms): 1763153809
duration time from system start(us): 1763153809208

4. 源码地址

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

推荐阅读
C++时间处理1-获取当前时间戳 C++时间处理1-获取当前时间戳 C++时间处理3-格式化时间戳 C++时间处理3-格式化时间戳 C++ 时间处理4-格式化时间区间 C++ 时间处理4-格式化时间区间

评论