0

I am in trouble with interpreting difftime quantity in a log I have produced:

I measure duration for some method call, and I log it, with this syntax:

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 ;  

where sqpis of ofstream type.

I get, where t_time (with type double) should be printed, the value 210.

Are those 210 seconds? Is it truncated, or floored?

How can I get result in seconds up to 2 floating points for instance?

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
kiriloff
  • 25,609
  • 37
  • 148
  • 229
  • 1
    Better yet, use `std::chrono`. – Mark Garcia Oct 11 '12 at 08:41
  • @MarkGarcia some C++11 i guess? who can compile C++11 BTW (which version of VS ?) ? – kiriloff Oct 11 '12 at 08:48
  • VS2010 has some support for c++11 (chrono is supported). VS2012 has full-blown support for c++11. – Mark Garcia Oct 11 '12 at 08:50
  • @MarkGarcia In fact VS2010 does **not** have `std::chrono`. *"VS2012 has full-blown support for c++11"* - well, for the library to be clear. Though even that is incomplete, missing at least C++11 mathematical functions and functions for controlling the floating point environment. – Christian Rau Oct 11 '12 at 09:53
  • @MarkGarcia do you know how to set precision with difftime to print in ostream ? i am using `outpt << std::fixed << std::setprecision(10) << (double) time << endl ;` and it is printing... 10 zeros after floating point, not improving precision. – kiriloff Oct 11 '12 at 13:49

2 Answers2

2

You need to use a timer with a higher resolution (if you can not use C++11). - Like this. For your case clockid_t - CLOCK_MONOTONIC.

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
Denis
  • 21
  • 2
1

difftime returns difference in seconds of type double http://www.cplusplus.com/reference/clibrary/ctime/difftime/ - see this for detailed explanations

spin_eight
  • 3,925
  • 10
  • 39
  • 61
  • thanks, how would you show in ofstream file two digits floating point precision then? – kiriloff Oct 11 '12 at 13:23
  • 1
    As difftime calculates difference of two values of type time_t(is integer value) you can`t get precision higher than one second. As difftime returns value of type double you can put it`s value in file in 2 digital point percision format using syntax like this: fprintf (pFile,"%.2lf", dif); or using object oriented i/o: cout.precision(2); cout << dif << endl; – spin_eight Oct 12 '12 at 05:37