1 /* Licensed under BSD-MIT - see LICENSE file for details */
2 #include <ccan/time/time.h>
6 #if !HAVE_CLOCK_GETTIME && !HAVE_CLOCK_GETTIME_IN_LIBRT
9 struct timespec time_now(void)
13 gettimeofday(&now, NULL);
14 ret.tv_sec = now.tv_sec;
15 ret.tv_nsec = now.tv_usec * 1000;
16 return TIME_CHECK(ret);
20 struct timespec time_now(void)
23 clock_gettime(CLOCK_REALTIME, &ret);
24 return TIME_CHECK(ret);
26 #endif /* HAVE_CLOCK_GETTIME || HAVE_CLOCK_GETTIME_IN_LIBRT */
28 struct timespec time_divide(struct timespec t, unsigned long div)
33 /* Dividing seconds is simple. */
34 res.tv_sec = TIME_CHECK(t).tv_sec / div;
37 /* If we can't fit remainder * 1,000,000,000 in 64 bits? */
38 #if 0 /* ilog is great, but we use fp for multiply anyway. */
40 if (bits + 30 >= 64) {
41 /* Reduce accuracy slightly */
42 rem >>= (bits - (64 - 30));
43 div >>= (bits - (64 - 30));
46 if (rem & ~(((uint64_t)1 << 30) - 1)) {
47 /* FIXME: fp is cheating! */
48 double nsec = rem * 1000000000.0 + t.tv_nsec;
49 res.tv_nsec = nsec / div;
51 ns = rem * 1000000000 + t.tv_nsec;
52 res.tv_nsec = ns / div;
54 return TIME_CHECK(res);
57 struct timespec time_multiply(struct timespec t, unsigned long mult)
61 /* Are we going to overflow if we multiply nsec? */
62 if (mult & ~((1UL << 30) - 1)) {
63 /* FIXME: fp is cheating! */
64 double nsec = (double)t.tv_nsec * mult;
66 res.tv_sec = nsec / 1000000000.0;
67 res.tv_nsec = nsec - (res.tv_sec * 1000000000.0);
69 uint64_t nsec = t.tv_nsec * mult;
71 res.tv_nsec = nsec % 1000000000;
72 res.tv_sec = nsec / 1000000000;
74 res.tv_sec += TIME_CHECK(t).tv_sec * mult;
75 return TIME_CHECK(res);
78 struct timespec time_check(struct timespec t, const char *abortstr)
80 if (t.tv_sec < 0 || t.tv_nsec >= 1000000000) {
82 fprintf(stderr, "%s: malformed time %li.%09li\n",
84 (long)t.tv_sec, (long)t.tv_nsec);
87 struct timespec old = t;
89 if (t.tv_nsec >= 1000000000) {
90 t.tv_sec += t.tv_nsec / 1000000000;
91 t.tv_nsec %= 1000000000;
96 fprintf(stderr, "WARNING: malformed time"
97 " %li seconds %li ns converted to %li.%09li.\n",
98 (long)old.tv_sec, (long)old.tv_nsec,
99 (long)t.tv_sec, (long)t.tv_nsec);