by arendtio · 6y ago · 0 comments
Last weekend I was playing around with some data. At first, I thought 'let's just write a line of awk and be done with it' and so I did. The execution took 20 seconds (about 17 million lines) and everything was fine.
Later that day, I came across another task which seemed too complex for an awk one-liner so I took two lines of R and was surprised when R was done within 5 seconds on the same data set.
I was happy because I found a faster tool than the one I had, but the lesson is, that just because you use a proven tool like awk, doesn't mean there aren't any better tools. Find out what works best for you.
[1]: https://brenocon.com/blog/2009/09/dont-mawk-awk-the-fastest-...
$ awk --version
GNU Awk 5.1.0, API: 3.0 (GNU MPFR 4.0.2, GNU MP 6.2.0)Interesting enough: LANG=C increased the performance of GNU awk a bit, but actually decreased the mawk performance.
I agree with the comment below. If you haven't already, try mawk instead of awk. It is often many times faster than awk (and other solutions).
Disclaimer: I don’t actually write any AWK, but learning it is on my bucket list.
AWK -> calculate the difference between every two lines:
awk -F ',' 'NR!=1{printf "%.0f\n", $1-ll}NR==1{print ""}{ll=$1}'
R -> Calculate the min, median, mean, and max: d<-scan("stdin", quiet=TRUE)
cat(min(d), max(d), median(d), mean(d), sep=" ")
AFAIK, calculating the difference to its previous line for every line should be faster for data that is not sorted. I didn't try to write that one in R though.I am sure there ways to make both things faster, I was just surprised as I didn't expect R to be faster with those two naive implementations.