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
|
#include <iostream>
#include <ctime>
#include <sys/time.h>
static void print_usage(const char *argv0) {
std::cerr
<< "Usage: " << argv0 << " [OPTIONS]\n"
<< " -h Show this help\n"
<< " -d Print deltas in seconds, not timestamps\n"
<< " -s Print tags in timestamp format\n"
<< " -t Print tags in local time format (default)\n"
<< std::flush;
}
enum Mode {
M_STAMP,
M_LOCALTIME,
M_DELTA,
};
int main(int argc, char **argv) {
// use std::cin, stdout, std::cerr
std::ios::sync_with_stdio(false);
Mode mode = M_LOCALTIME;
for (int i = 1; i < argc; i++) {
if (argv[i][0] != '-') {
std::cerr << "Unrecognised argument: '" << argv[i] << "'" << std::endl;
print_usage(argv[0]);
return 1;
}
for (int j = 1; argv[i][j]; j++) {
switch (argv[i][j]) {
case 'h': print_usage(argv[0]); return 0;
case 'd': mode = M_DELTA; break;
case 's': mode = M_STAMP; break;
case 't': mode = M_LOCALTIME; break;
default: print_usage(argv[0]); return 1;
}
}
}
struct timeval tv;
double prevtm;
if (mode == M_DELTA) {
gettimeofday(&tv, nullptr);
prevtm = tv.tv_sec + tv.tv_usec * 1.0e-6;
}
std::string line;
while (std::getline(std::cin, line)) {
gettimeofday(&tv, nullptr);
switch (mode) {
case M_STAMP:
printf("%.6lf %s\n", tv.tv_sec + tv.tv_usec * 1.0e-6, line.data());
break;
case M_LOCALTIME: {
const struct tm *tm = localtime(&tv.tv_sec);
char buffer[128];
ssize_t nw = strftime(buffer, sizeof buffer - 7, "%Y-%m-%d %H:%M:%S.", tm);
for (int i = 5; i >= 0; i--) {
buffer[nw + i] = '0' + tv.tv_usec % 10;
tv.tv_usec /= 10;
}
buffer[nw + 6] = '\0';
printf("%s %s\n", buffer, line.data());
break;
}
case M_DELTA: {
double tm = tv.tv_sec + tv.tv_usec * 1.0e-6;
printf("%.6lf %s\n", tm - prevtm, line.data());
prevtm = tm;
break;
}
}
}
}
|