aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn Ankarström <john@ankarstrom.se>2020-12-12 16:12:30 +0100
committerJohn Ankarström <john@ankarstrom.se>2020-12-12 16:12:30 +0100
commit119904b4ecd8684e27db5af54e8f42082749324f (patch)
treee3dde465f6596652f5e965ac358d887f4319ead0
downloadtyp-119904b4ecd8684e27db5af54e8f42082749324f.tar.gz
First commit
-rw-r--r--Makefile2
-rw-r--r--typ.c64
2 files changed, 66 insertions, 0 deletions
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 <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);
+}