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
|
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
double atime() {
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
return now.tv_sec + now.tv_nsec * 1e-9;
}
int main() {
double *wt;
int c, l, t, ttyfd, wi, *wl, ws;
struct termios orig, raw;
ws = 100; /* allocated number of words */
wl = malloc(ws * sizeof(int)); /* word lengths */
if (wl == NULL) err(1, "malloc");
wt = malloc(ws * sizeof(double)); /* word times */
if (wt == NULL) err(1, "malloc");
l = 0; /* current word length */
wi = 0; /* number of current word in order */
/* enter "raw" mode */
ttyfd = open("/dev/tty", O_RDWR);
if (ttyfd == -1) err(1, "open");
tcgetattr(ttyfd, &orig);
raw = orig;
raw.c_lflag &= ~(ICANON);
tcsetattr(ttyfd, TCSANOW, &raw);
/* read loop */
while ((c = getchar()) != EOF) {
if (l == 0)
t = atime(); /* current word time */
if (c == ' ' || c == '\n') {
wl[wi] = l;
wt[wi] = atime() - t;
l = 0;
wi++;
} else
l++;
if (c == '\n')
break;
}
/* print statistics */
double tt = 0;
int tl = 0;
for (int i = 0; i < wi; i++) {
tt += wt[i];
tl += wl[i];
}
printf("%f seconds per word\n", tt / wi);
printf("%f seconds per word character\n", tt / tl);
/* restore original terminal settings */
tcsetattr(ttyfd, TCSANOW, &orig);
}
|