How to printf a time_t variable as a floating point number?

soneangel picture soneangel · Apr 13, 2010 · Viewed 17.2k times · Source

I'm using a time_t variable in C (openMP enviroment) to keep cpu execution time...I define a float value sum_tot_time to sum time for all cpu's...I mean sum_tot_time is the sum of cpu's time_t values. The problem is that printing the value sum_tot_time it appear as an integer or long, by the way without its decimal part!

I tried in these ways:

  1. to printf sum_tot_time as a double being a double value
  2. to printf sum_tot_time as float being a float value
  3. to printf sum_tot_time as double being a time_t value
  4. to printf sum_tot_time as float being a time_t value

Answer

vladr picture vladr · Apr 13, 2010

The resolution of time_t is at most one second on most platforms. That is, on most platforms, time_t will be an integer (32- or 64-bit) value counting the number of seconds elapsed since midnight of Jan 1st 1970 (UTC), and can only achieve one-second resolution.

Therefore, a sum of time_t values will also only exhibit one-second resolution (no decimal part, even after converting to double.)

The above having been said, what native or OpenMP call are you using to obtain the time_t values that you are attempting to accumulate?

If using either the native *nix getrusage() call to fill out an rusage structure (provided your platform supports it) with user/kernel times, or if using gettimeofday() to get wall time, then use both the tv_sec and tv_usec fields of struct timeval to generate a double value (of millisecond-or-better resolution, typically), and use that instead of time_t in your calculations:

struct timeval {
        time_t          tv_sec;         /* seconds */
        suseconds_t     tv_usec;        /* microseconds */
};

Correspondingly, you can use GetThreadTimes/GetProcessTimes for user/kernel times or _ftime for wall time on Windows platforms, then combine FILETIME::dwHighDateTime/dwLowDateTime.