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