From 119904b4ecd8684e27db5af54e8f42082749324f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Ankarstr=C3=B6m?= Date: Sat, 12 Dec 2020 16:12:30 +0100 Subject: First commit --- Makefile | 2 ++ typ.c | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 Makefile create mode 100644 typ.c diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..cdcdd17 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +typ: typ.c + gcc -o $@ $< diff --git a/typ.c b/typ.c new file mode 100644 index 0000000..542476d --- /dev/null +++ b/typ.c @@ -0,0 +1,64 @@ +#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); +} -- cgit v1.2.3