如何格式化std :: chrono持续时间? [英] How to format std::chrono durations?

查看:263
本文介绍了如何格式化std :: chrono持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有方便的方法将 std :: chrono :: duration 格式化为指定格式?

Is there a convenient way to format std::chrono::duration to a specified format?

std::chrono::high_resolution_clock::time_point now, then;
then = std::chrono::high_resolution_clock::now();
// ...
now = std::chrono::high_resolution_clock::now();
auto duration = now - then;

// base in microseconds:
auto timeInMicroSec =
      std::chrono::duration_cast<std::chrono::microseconds>(duration);

如何格式化 timeInMicroSec ss :: ms :: us

推荐答案

一个人可以使用以下内容:

One can use something like:

#include <iomanip>
#include <sstream>

//...

auto c(timeInMicroSec.count());
std::ostringstream oss;
oss << std::setfill('0')          // set field fill character to '0'
    << (c % 1000000000) / 1000000 // format seconds
    << "::"
    << std::setw(3)               // set width of milliseconds field
    << (c % 1000000) / 1000       // format milliseconds
    << "::"
    << std::setw(3)               // set width of microseconds field
    << c % 1000;                  // format microseconds
auto formatted(oss.str());

这篇关于如何格式化std :: chrono持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆