summaryrefslogtreecommitdiff
path: root/timeadd.c
blob: e43c95101ceab50ba90e86dc0093fda3b2a064b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
 * Adds a timestamp before every line.
 *
 * Author: Peter Wu <lekensteyn@gmail.com>
 * Date: 2013-10-04
 */
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>

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, 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');

		clock_gettime(CLOCK_MONOTONIC, &tp[tp_i]);

		if (newline)
			*newline = '\0';

		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);
	}

	return 0;
}