开发者

UNIX time in decimals in C

How can I get UNIX time in decimals in C, like Python does that?

What I have in C using http://bytes.com/topic/c/answers/221083-how-show-unix-time-c

me@laptop$ ./time 
1299556464

What I want and it works in Python:

开发者_开发百科>>> time.time()
1299556249.3973091


Everything's open source, it's easy to find out what Python's doing.

From Python/Modules/timemodule.c,

static double
floattime(void)
{
    /* There are three ways to get the time:
      (1) gettimeofday() -- resolution in microseconds
      (2) ftime() -- resolution in milliseconds
      (3) time() -- resolution in seconds

There is also the POSIX function clock_gettime which has resolution in nanoseconds.


#include <sys/time.h>
struct timeval tv;

gettimeofday(&tv, 0);

printf("%d.%06d", (int)tv.tv_sec, (int)tv.tv_usec);  // Corrected -> to . (it's late!)

Officially, POSIX 2008 has deprecated gettimeofday(), but it is likely to be around for the foreseeable future. The casts are safe enough for the next quarter century or so; after that, there could be problems with 32-bit int types. The second argument is strictly a null pointer; the compiler will take care of that coercion. Any non-null value for the pointer has an implementation defined meaning. The function always returns 0; there is no virtue in testing its return value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜