How to printf a time_t variable as a floating point number?
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 mea开发者_运维知识库n 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:
- to printf sum_tot_time as a double being a double value
- to printf sum_tot_time as float being a float value
- to printf sum_tot_time as double being a time_t value
- to printf sum_tot_time as float being a time_t value
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
.
I'm not sure if you have access to standard *nix system calls ( or if this is relevant to specifically to what you're doing ), but if you do you can use the timeval struct
and gettimeofday
. For example, to print out a timestamp with six decimal places of precision which produces a tcpdump style time stamp ( courtesy of Steven UNP )
#include "unp.h"
#include <time.h>
char *
gf_time(void)
{
struct timeval tv;
time_t t;
static char str[30];
char *ptr;
if (gettimeofday(&tv, NULL) < 0)
err_sys("gettimeofday error");
t = tv.tv_sec; /* POSIX says tv.tv_sec is time_t; some BSDs don't agree. */
ptr = ctime(&t);
strcpy(str, &ptr[11]);
/* Fri Sep 13 00:00:00 1986\n\0 */
/* 0123456789012345678901234 5 */
snprintf(str+8, sizeof(str)-8, ".%06ld", tv.tv_usec);
return(str);
}
精彩评论