【问题标题】:get boost::posix_time::time_duration in seconds以秒为单位获取 boost::posix_time::time_duration
【发布时间】:2012-02-08 13:27:57
【问题描述】:

我正在使用 boost::posix_time::ptime 来测量我的模拟运行时间以及其他用途。

假设

boost::posix_time::ptime start, stop;
boost::posix_time::time_duration diff;
start = boost::posix_time::microsec_clock::local_time();
sleep(5);
stop = boost::posix_time::microsec_clock::local_time();
diff = stop - stop;

现在

std::cout << to_simple_string( diff ) << std::endl;

hh:mm:ss.ssssss 格式返回时间,我也想以ss.sssssss 格式返回时间。

为此,我尝试过

boost::posix_time::time_duration::sec_type x = diff.total_seconds();

但这给了我 ss 格式的答案,seconds() 返回返回归一化的秒数 (0..60)。

我的问题是如何获得格式为 ss.ssssss 的模拟时间(以秒为单位)?

编辑

我能够做到:

 std::cout << diff.total_seconds() << "." <<  diff.fractional_seconds() << std::endl;

有什么优雅的东西可以绘制 ss.sssssss 吗?

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    total_seconds() 返回一个 long 值,该值未标准化为 0..60 秒。

    那么就这样做吧:

    namespace bpt = boost::posix_time;
    
    int main(int , char** )
    {
        bpt::ptime start, stop;
        start = bpt::microsec_clock::local_time();
        sleep(62);
        stop = bpt::microsec_clock::local_time();
    
        bpt::time_duration dur = stop - start;
    
        long milliseconds = dur.total_milliseconds();
    
        std::cout << milliseconds << std::endl; // 62000
    
        // format output with boost::format
        boost::format output("%.2f");
        output % (milliseconds/1000.0);
        std::cout << output << std::endl; // 62.00
    }
    

    【讨论】:

    • 感谢您的重播。根据您的示例,我想要以下输出:62.0000 (ss.ssssss)。有可能吗?
    • @Eagle:我使用boost::format 添加了一个包含您所需输出的示例。希望对您有所帮助。
    【解决方案2】:
    // whatever time you have (here 1second)
    boost::posix_time::ptime pt = boost::posix_time::from_time_t( 1 ); 
    // subtract 0 == cast to duration
    boost::posix_time::time_duration dur = pt - boost::posix_time::from_time_t(0); 
    // result in ms
    uint64_t ms = dur.total_milliseconds();
    // result in usec
    uint64_t us = dur.total_microseconds();
    // result in sec
    uint64_t  s = dur.total_seconds();
    std::cout << "s = " << s << ", ms = " << ms << ", us = " << us << std::endl;
    

    s = 1,ms = 1000,us = 1000000

    【讨论】:

      【解决方案3】:

      我看到的最直接的方式是这样的输出,其余时间按照 nabulke 的帖子进行计算:

      #include <iomanip>
      double dseconds = dur.total_milliseconds() / 1000. ;
      
      std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(3);
      std::cout << dseconds << std::endl;
      

      您想用浮点数表示时间,因此最好实际使用浮点数并应用标准流格式化操纵器。

      【讨论】:

      • 成功了,你是对的。我自己试过了,但我忘记了“。” ....所以我得到了整数
      猜你喜欢
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      相关资源
      最近更新 更多