【问题标题】:C++ time.h difftimeC++ time.h difftime
【发布时间】:2012-10-01 21:03:57
【问题描述】:

我无法解释我生成的日志中的 difftime 数量:

我测量一些方法调用的持续时间,并使用以下语法记录它:

time_t end, start ;

time(&start);

obj->sqp_func(this);

time(&end);

t_time = difftime(end, start) ;

sqp << "time " << endl ;
sqp << (double) end <<  endl ;
sqp << (double) start << endl ; 
sqp << (double) t_time << endl ;  

其中sqpofstream类型。

我知道了,应该在哪里打印 t_time(类型为 double),值 210。

是 210 秒吗?它是被截断的,还是被截断的?

例如,如何在几秒钟内获得最多 2 个浮点数的结果?

【问题讨论】:

  • 更好的是,使用std::chrono
  • @MarkGarcia 我猜是一些 C++11?谁可以编译C++11 BTW(哪个版本的VS?)?
  • VS2010 对 c++11 有一些支持(支持chrono)。 VS2012 全面支持 c++11。
  • @MarkGarcia 实际上 VS2010 没有std::chrono“VS2012 全面支持 c++11” - 好吧,为了清楚这个库。虽然这还不完整,但至少缺少 C++11 数学函数和用于控制浮点环境的函数。
  • @MarkGarcia 你知道如何使用 difftime 设置精度以在 ostream 中打印吗?我正在使用outpt &lt;&lt; std::fixed &lt;&lt; std::setprecision(10) &lt;&lt; (double) time &lt;&lt; endl ;,它正在打印...浮点后有10个零,没有提高精度。

标签: c++ time truncate floor


【解决方案1】:

您需要使用更高分辨率的计时器(如果您不能使用 C++11)。 -Like this。对于您的情况clockid_t - CLOCK_MONOTONIC

【讨论】:

    【解决方案2】:

    difftime 返回 double 类型的 以秒为单位的差异 http://www.cplusplus.com/reference/clibrary/ctime/difftime/ - 详细解释请看这里

    【讨论】:

    • 谢谢,那么你将如何在 ofstream 文件中显示两位浮点精度?
    • 由于 difftime 计算两个 time_t 类型值的差异(是整数值),您可以使用如下语法以 2 个数字点精度格式在文件中t get precision higher than one second. As difftime returns value of type double you can put its 值:fprintf (pFile,"%. 2lf", 差异);或使用面向对象的 i/o:cout.precision(2); cout
    猜你喜欢
    • 2016-02-08
    • 1970-01-01
    • 2013-06-07
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多