ctdb-build: Add generation of Samba-style version.h
[Samba.git] / ctdb / lib / util / util_time.c
blob13ddfdb2b6e5b0094bf5bc93c725f81299d48339
1 /*
2 functions taken from samba4 for quick prototyping of ctdb. These are
3 not intended to remain part of ctdb
4 */
6 #include "includes.h"
7 #include "system/time.h"
8 #include "system/filesys.h"
11 /**
12 return a zero timeval
14 struct timeval timeval_zero(void)
16 struct timeval tv;
17 tv.tv_sec = 0;
18 tv.tv_usec = 0;
19 return tv;
22 /**
23 return True if a timeval is zero
25 bool timeval_is_zero(const struct timeval *tv)
27 return tv->tv_sec == 0 && tv->tv_usec == 0;
30 /**
31 return a timeval for the current time
33 struct timeval timeval_current(void)
35 struct timeval tv;
36 gettimeofday(&tv, NULL);
37 return tv;
40 double timeval_elapsed(struct timeval *tv)
42 struct timeval tv2 = timeval_current();
43 return (tv2.tv_sec - tv->tv_sec) +
44 (tv2.tv_usec - tv->tv_usec)*1.0e-6;
47 /**
48 return a timeval struct with the given elements
50 _PUBLIC_ struct timeval timeval_set(uint32_t secs, uint32_t usecs)
52 struct timeval tv;
53 tv.tv_sec = secs;
54 tv.tv_usec = usecs;
55 return tv;
58 _PUBLIC_ int timeval_compare(const struct timeval *tv1, const struct timeval *tv2)
60 if (tv1->tv_sec > tv2->tv_sec) return 1;
61 if (tv1->tv_sec < tv2->tv_sec) return -1;
62 if (tv1->tv_usec > tv2->tv_usec) return 1;
63 if (tv1->tv_usec < tv2->tv_usec) return -1;
64 return 0;
67 _PUBLIC_ struct timeval timeval_until(const struct timeval *tv1,
68 const struct timeval *tv2)
70 struct timeval t;
71 if (timeval_compare(tv1, tv2) >= 0) {
72 return timeval_zero();
74 t.tv_sec = tv2->tv_sec - tv1->tv_sec;
75 if (tv1->tv_usec > tv2->tv_usec) {
76 t.tv_sec--;
77 t.tv_usec = 1000000 - (tv1->tv_usec - tv2->tv_usec);
78 } else {
79 t.tv_usec = tv2->tv_usec - tv1->tv_usec;
81 return t;
84 static struct timeval timeval_add(const struct timeval *tv,
85 uint32_t secs, uint32_t usecs)
87 struct timeval tv2 = *tv;
88 const unsigned int million = 1000000;
89 tv2.tv_sec += secs;
90 tv2.tv_usec += usecs;
91 tv2.tv_sec += tv2.tv_usec / million;
92 tv2.tv_usec = tv2.tv_usec % million;
93 return tv2;
97 _PUBLIC_ struct timeval timeval_current_ofs(uint32_t secs, uint32_t usecs)
99 struct timeval tv = timeval_current();
100 return timeval_add(&tv, secs, usecs);