summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPeter Wu <lekensteyn@gmail.com>2013-10-04 19:31:48 +0200
committerPeter Wu <lekensteyn@gmail.com>2013-10-04 19:31:48 +0200
commitd4e60b0737b1bc28705561321d1b851fa2f46e2a (patch)
treea048f1376dc2268968b3f995612c0e2bca46003c
parent521a4d6351b6dadd0a9ebe2db9acf78d4df322af (diff)
downloadc-files-d4e60b0737b1bc28705561321d1b851fa2f46e2a.tar.gz
timeadd: support time difference
-rw-r--r--timeadd.c67
1 files changed, 61 insertions, 6 deletions
diff --git a/timeadd.c b/timeadd.c
index 061a0ae..d2f0159 100644
--- a/timeadd.c
+++ b/timeadd.c
@@ -8,22 +8,77 @@
#include <time.h>
#include <string.h>
#include <stdlib.h>
+#include <unistd.h>
+#include <stdbool.h>
-int main() {
+static void print_usage(const char *program_name) {
+ fprintf(stderr, "Usage: %s [-d]\n", program_name);
+ fputs("Options:\n"
+ " -d Display time difference instead of a monotonic clock\n",
+ stderr);
+}
+
+struct timespec timediff(struct timespec begin, struct timespec end) {
+ struct timespec diff;
+
+ diff.tv_sec = end.tv_sec - begin.tv_sec;
+ diff.tv_nsec = end.tv_nsec - begin.tv_nsec;
+
+ if (end.tv_nsec < begin.tv_nsec) {
+ /* alternative case: 3.2 -> 4.1, diff is 0.9 */
+ diff.tv_sec--;
+ diff.tv_nsec += 1000000000;
+ }
+
+ return diff;
+}
+
+int main(int argc, char **argv) {
+ const char *out_format;
char buf[4096];
+ struct timespec tp[2] = { { 0 } };
+ int tp_i = 0;
+ int opt;
+ bool diff = false;
+
+ while ((opt = getopt(argc, argv, "d")) != -1) {
+ switch (opt) {
+ case 'd':
+ diff = true;
+ break;
+ default:
+ print_usage(argv[0]);
+ return 1;
+ }
+ }
+
+ if (diff) {
+ out_format = "[%+6lld.%06lu] %s\n";
+ } else {
+ out_format = "[%6llu.%06lu] %s\n";
+ }
while (fgets(buf, sizeof(buf), stdin) != NULL) {
char *newline = strrchr(buf, '\n');
- struct timespec tp;
- clock_gettime(CLOCK_MONOTONIC, &tp);
+ clock_gettime(CLOCK_MONOTONIC, &tp[tp_i]);
if (newline)
*newline = '\0';
- printf("[%5llu.%06lu] %s\n",
- (long long) tp.tv_sec,
- tp.tv_nsec / 1000,
+ if (diff) {
+ /* new time is available in "tp_i". Old time (and print
+ * target) is the inverse of tp_i (modulo 2). */
+ tp[tp_i ^ 1] = timediff(tp[tp_i ^ 1], tp[tp_i]);
+ /* flip such that "tp_i" refers to difference time and
+ * inverse "tp_i" points to the new time (in the next
+ * iteration it becomes the old time) */
+ tp_i ^= 1;
+ }
+
+ printf(out_format,
+ (long long) tp[tp_i].tv_sec,
+ tp[tp_i].tv_nsec / 1000,
buf);
}