summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRusty Russell <rusty@rustcorp.com.au>2013-10-28 21:57:16 +1030
committerRusty Russell <rusty@rustcorp.com.au>2013-10-28 21:57:16 +1030
commitfe5952874bfb47b8d2c087c93d2149aea6ec2f44 (patch)
tree2232a89b1926c3a2022b26e6d7c56716113637a5
parent96a1ebd3354ef6250e94b509b4e0c0f1ea7e67bb (diff)
time: to/from sec conversions.
Trivial, but they make coding easier and more predictable. Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
-rw-r--r--ccan/time/test/run.c8
-rw-r--r--ccan/time/time.h35
2 files changed, 42 insertions, 1 deletions
diff --git a/ccan/time/test/run.c b/ccan/time/test/run.c
index 7f436600..21c72213 100644
--- a/ccan/time/test/run.c
+++ b/ccan/time/test/run.c
@@ -6,7 +6,7 @@ int main(void)
{
struct timespec t1, t2, t3, zero = { 0, 0 };
- plan_tests(58);
+ plan_tests(61);
/* Test time_now */
t1 = time_now();
@@ -51,6 +51,12 @@ int main(void)
t3 = time_sub(t2, t2);
ok1(time_eq(t3, zero));
+ /* time_from_sec / time_to_sec */
+ t3 = time_from_sec(500);
+ ok1(t3.tv_sec == 500);
+ ok1(t3.tv_nsec == 0);
+ ok1(time_to_sec(t3) == 500);
+
/* time_from_msec / time_to_msec */
t3 = time_from_msec(500);
ok1(t3.tv_sec == 0);
diff --git a/ccan/time/time.h b/ccan/time/time.h
index 5bb1ad5b..e4298d07 100644
--- a/ccan/time/time.h
+++ b/ccan/time/time.h
@@ -211,6 +211,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
*
@@ -276,6 +294,23 @@ static inline uint64_t time_to_nsec(struct timespec t)
}
/**
+ * 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
*