C++ 时间处理-格式化时间区间

发布于:2024-05-23 ⋅ 阅读:(165) ⋅ 点赞:(0)

1. 关键词

C++ 时间处理 格式化时间区间 跨平台 支持秒/微秒/毫秒

使用场景:对执行时间、执行时长的格式化输出。

2. timeutil.h

#include <string>
#include <cstdint>

/**
 * @brief Format a time duration to a human-readable string.
 *
 * @param seconds the duration in seconds.
 * @return std::string the formatted string.
 */
std::string fmt_timeduration_s(uint64_t seconds);
/**
 * @brief Format a time duration to a human-readable string.
 *
 * @param microseconds the duration in microseconds.
 * @return std::string the formatted string.
 */
std::string fmt_timeduration_ms(uint64_t microseconds);
/**
 * @brief Format a time duration to a human-readable string.
 *
 * @param nanoseconds the duration in nanoseconds.
 * @return std::string the formatted string.
 */
std::string fmt_timeduration_us(uint64_t nanoseconds);

3. timeutil.cpp

#include "timeutil.h"
#include <iomanip>

constexpr static int ONE_MIN = 60;
constexpr static int ONE_HOUR = 60 * ONE_MIN;
constexpr static int ONE_DAY = 24 * ONE_HOUR;

std::string fmt_timeduration_s(uint64_t seconds)
{
    std::string text;
    if (seconds > ONE_DAY)
    {
        uint64_t day = seconds / ONE_DAY;
        text += std::to_string(day) + "d:";
    }

    if (seconds > ONE_HOUR)
    {
        uint64_t hour = (seconds % ONE_DAY) / ONE_HOUR;
        text += fmt_uint(hour, 2) + "h:";
    }

    if (seconds > ONE_MIN)
    {
        uint64_t min = (seconds % ONE_HOUR) / ONE_MIN;
        text += fmt_uint(min, 2) + "m:";
    }

    uint64_t sec = (seconds % ONE_MIN);
    text += fmt_uint(sec, 2) + "s";

    return text;
}

std::string fmt_timeduration_ms(uint64_t microseconds)
{
    auto s = microseconds / THOUSAND;
    auto ms = microseconds % THOUSAND;
    auto text = fmt_timeduration_s(s);
    text += "." + fmt_uint(ms, 3) + "ms";
    return text;
}

std::string fmt_timeduration_us(uint64_t nanoseconds)
{
    auto s = nanoseconds / MILLION;
    auto ms = nanoseconds % MILLION;
    auto text = fmt_timeduration_s(s);
    text += "." + fmt_uint(ms, 6) + "us";
    return text;
}

4. 测试代码

#include "timeutil.h"
#include "common.hpp"

void TestFormatTime()
{
    PrintSubTitle("TestFormatTime");
    // duration
    // 180100345), "2d:2h:1m:40s:345ms"
    std::cout << "duration1: " << cutl::fmt_timeduration_s(180100) << std::endl;
    std::cout << "duration2: " << cutl::fmt_timeduration_ms(180100345) << std::endl;
    std::cout << "duration3: " << cutl::fmt_timeduration_us(180100345678) << std::endl;
}

5. 运行结果

-------------------------------------------TestFormatTime-------------------------------------------
duration1: 2d:02h:01m:40s
duration2: 2d:02h:01m:40s.345ms
duration3: 2d:02h:01m:40s.345678us

6. 源码地址

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


网站公告

今日签到

点亮在社区的每一天
去签到