]> git.ozlabs.org Git - ccan/blobdiff - ccan/time/time.h
time: to/from sec conversions.
[ccan] / ccan / time / time.h
index a9936b50bdd9a68399f4ae09acfad5d931f0580a..e4298d07055d1ab66ad816a042ede0bcf9720b26 100644 (file)
@@ -210,6 +210,24 @@ struct timespec time_divide(struct timespec t, unsigned long div);
  */
 struct timespec time_multiply(struct timespec t, unsigned long mult);
 
+/**
+ * time_to_sec - return number of seconds
+ * @t: a time
+ *
+ * It's often more convenient to deal with time values as seconds.
+ * Note that this will fit into an unsigned 32-bit variable if it's a
+ * time of less than about 136 years.
+ *
+ * Example:
+ *     ...
+ *     printf("Forking time is %u sec\n",
+ *            (unsigned)time_to_sec(forking_time()));
+ */
+static inline uint64_t time_to_sec(struct timespec t)
+{
+       return t.tv_sec;
+}
+
 /**
  * time_to_msec - return number of milliseconds
  * @t: a time
@@ -275,6 +293,23 @@ static inline uint64_t time_to_nsec(struct timespec t)
        return nsec;
 }
 
+/**
+ * time_from_sec - convert seconds to a timespec
+ * @msec: time in seconds
+ *
+ * Example:
+ *     // 1 minute timeout
+ *     #define TIMEOUT time_from_sec(60)
+ */
+static inline struct timespec time_from_sec(uint64_t sec)
+{
+       struct timespec t;
+
+       t.tv_nsec = 0;
+       t.tv_sec = sec;
+       return TIME_CHECK(t);
+}
+
 /**
  * time_from_msec - convert milliseconds to a timespec
  * @msec: time in milliseconds
@@ -334,6 +369,7 @@ static inline struct timespec time_from_nsec(uint64_t nsec)
  *     struct timeval tv;
  *
  *     tv = timespec_to_timeval(time_now());
+ *     printf("time = %lu.%06u\n", (long)tv.tv_sec, (int)tv.tv_usec);
  */
 static inline struct timeval timespec_to_timeval(struct timespec ts)
 {
@@ -352,6 +388,7 @@ static inline struct timeval timespec_to_timeval(struct timespec ts)
  *     struct timespec ts;
  *
  *     ts = timeval_to_timespec(tv);
+ *     printf("timespec = %lu.%09lu\n", (long)ts.tv_sec, (long)ts.tv_nsec);
  */
 static inline struct timespec timeval_to_timespec(struct timeval tv)
 {