我正在使用boost::posix_time::ptime
来衡量我的模拟运行时和其他内容。
assuimg
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?
答案 0 :(得分:15)
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
}
答案 1 :(得分:1)
我看到的最直接的方式是这样的输出,其余的时间计算沿着nabulke的帖子:
#include <iomanip>
double dseconds = dur.total_milliseconds() / 1000. ;
std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(3);
std::cout << dseconds << std::endl;
您希望以浮点数表示时间,因此最好实际使用一个并应用标准流格式操纵器。
答案 2 :(得分:1)
// 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