162 points · by rachitnigam · 7y ago · 185 comments
I actually wrote a comment (in 2013, but the page I'm referencing doesn't appear to have changed one bit) where I shared my experience looking at haskell.org's introduction that was filled with FUD regarding C and how Haskell was so much better and faster:
https://news.ycombinator.com/item?id=5090808
Maybe if they had actually tried to teach me the language instead of that bad faith "used car salesman" tactic I'd be writing Haskell these days.
I think it's about the same for pretty much any language in the "statically typed, compiled" camp. You'll see "faster than C" claims for Rust and Go as well, for example.
Meanwhile Rust is genuinely competitive with C performance-wise and thanks to generics and things like more aggressive inlining can actually equal or even beat C without requiring esoteric micro-optimizations. Of course the drawback is that writing Rust code is significantly more complicated and more restrictive.
I feel that you have mis-characterised a whole community, very few of whom care to make Haskell faster than C and overwhelmingly share your view that "C-grade performance is not required".
Further, in the posts I've read of people comparing to C, if anything C is held up as the benchmark as a mark of respect - not as something to cheat against, not to try to say that Haskell is better. Indeed Haskell's FFI out to C is really nice, and demonstrates the pragmatic side of this ivory-tower language :)
This post first embraces its clickbait article and then highlights that even though the Haskell version may be faster on multicore systems (at least for ascii - the unicode version may be incorrect wrt. unicode spaces), but that in practical situations without caching this may not provide any benefit. You're acting as if OP submitted his binary to Apple, *BSD and all the Linux distros with a pull request saying his is better! It's a fun post golfing some Haskell performance issues.
Or as Feynman put it:
The first principle is that you must not fool yourself — and you are the easiest person to fool.
The main point here is clearly not to sell the existing tool on the sole consideration of binary execution performances. As the article say, with Haskell you can produce more reliable software, thanks to a strong typing, and use higher abstraction levels. Even with a significant loss in performance, this can be a good trade off (depending on the project type of course).
So the point here is that you can have descent performance with a state of the art "high-level garbage-collected runtime-based language".
"is wildly incorrect" would be more accurate.
Having to use a syntax extension explicitly to forgo laziness feels like cheating to me... But then I have never used Haskell so perhaps that's actually normal.
Pretty much any non-trivial Haskell program (and many trivial ones too) will have !'s in various places to force something to be strict, and to use the ! syntax you do need to add a pragma. Those pragmas are what let Haskell evolve new features without breaking backward compatibility, so Haskell programs tend to have a lot of them. Perhaps one day we'll have a new standard (it's been 19 years since the last one) which will include some of the pragmas by default. In the meanwhile, it's possible to turn the common ones on project-wide and just forget about them.
Does Haskell 2010 not count?
You can do it without the extension, but it'll turn ugly really quick (lots of uses of the "seq" function everywhere).
In general, the Haskell community is very tolerant of language extensions (people will recommend you enable about a dozen of them in every project), so this is pretty standard.
The `seq` function achieves the same end and is in the standard library. There's nothing cheating about it. The bang patterns extension just provides some nicer syntax for it.
Whereas for single-core the C code would be simpler than the optimized single-core Haskell code presented here.
(You could use green threads in C - or something similar, though to be honest counting words in a file is a bit of an annoying problem for parallelism)
type t = { mutable words: int; mutable chars: int; mutable lines: int; mutable in_word: bool ; mutable finished: bool};;
let () =
match Core.Sys.argv with
| [| prog_name |] -> Core.Printf.eprintf "Usage: %s file1 file2 ...\n" prog_name
| _ -> (
let args = Core.Array.slice Core.Sys.argv 1 @@ Core.Array.length Core.Sys.argv in
let buf_size = 65536 in (* 64 KB -> Caml IO buffer size *)
let buf = Core.Bytes.create buf_size in
Core.Array.fold args ~init:() ~f:(fun _ file ->
Core.In_channel.with_file file ~f:(fun in_ch ->
let c = { words = 0; chars = 0; lines = 0; in_word = false; finished = false } in
let set_words () = if c.in_word then c.words <- c.words + 1 in
while not c.finished do
let len = Core.In_channel.input in_ch ~buf ~pos:0 ~len:buf_size |> Core.Int.to_int in
if len > 0 then (
for i = 0 to (len - 1) do
match (Core.Caml.Bytes.get buf i) with
| ' ' | '\t' | '\r' -> (c.chars <- c.chars + 1; set_words (); c.in_word <- false)
| '\n' -> (c.chars <- c.chars + 1; set_words (); c.in_word <- false; c.lines <- c.lines + 1)
| _ -> (c.chars <- c.chars + 1; c.in_word <- true)
done
) else ( c.finished <- true )
done;
set_words ();
Core.Printf.printf "%s -> lines: %d, words: %d, characters: %d\n" file c.lines c.words c.chars)))
;;
Testing: $ ls -lh test_file.txt
-rw-r--r-- 1 user group 508M Oct 16 12:01 test_file.txt
$ time wc test_file.txt
4863460 54621760 532480000 test_file.txt
real 0m3.368s
user 0m3.137s
sys 0m0.195s
#Ocaml version:
$ time ./wcl.native test_file.txt
test_file.txt -> lines: 4863460, words: 54621760, characters: 532480000
real 0m2.480s
user 0m2.345s
sys 0m0.123s $ time wc w.txt
3156098 6312196 380648004 w.txt
real 0m1.358s
user 0m1.277s
sys 0m0.066s
... with one line of q (best of three): q)\t g:{(sum[1<deltas where x]+sum[not x:max x],0),sum max x 0 1}0x0d0a2009=\:read1 `:w.txt
783
q)g
380648004i
6312196
3156098i
783msec: almost twice as fast!(b:#a;b++/,/a=/:" ";b+#,/a)
A best of five run of the system's wc takes 0.042s, vs 0.028s for the OCaml version.
I was going to say that it is unreadable, after spending a bit trying to understand it, (for someone that knows no ocaml) it actually is not. Only things I'm unsure are the ~ symbol and <-. What do they do?
edit: <- is just mutating assignment. I thought that ~ introduced named arguments but doesn't seem right.
You mean before the JVM has started up. One could compile Clojure with GraalVM to eliminate startup time.
The way I generally use "wc" is inside a somewhat complex command line, with commands preceding it. As in "feeding characters" to it.
There is a reason why "wc" is not multithreaded: it just can't. It must work sequentially, because in the general case the input of "wc" cannot be skipped over.
This is one of the two big assumptions that are made by the author ("wc works only for files, so we can lseek") -- the second, identified by the author, being that the underlying hardware and filesystem must support concurrent access to the same location efficiently.
Eh what? Word counting is embarrassingly parallel, at least for files.
You start up k threads each working on its own chunk of the file, assuming that there is a word boundary at the start of its chunk. Then you sum up the total word count but inspect whether the chunk boundaries actually were word boundaries, and subtract 1 each time this was violated.
wc does not make the presumption that it is working on a file that can be seeked into (and, more importantly, re-wound). in c++ terms, it behaves as though the source it is reading from is an "input iterator"[1].
if you are piping into wc, then you'll never be able to parallelise it. word counting a file is the edge case here, not the general use.
[1] - https://en.cppreference.com/w/cpp/named_req/InputIterator
True; and "wc" works not just on files. "wc" also works on character devices, on streams of data that cannot be randomly accessed.
(Of course wc could switch to a multithreaded algorithm while working on files, but the point did make sense.)
Used Unix every day for 20 years and I'd say 90% of WC use cases is read from a pipe
> The program takes more than a few minutes and quickly spikes up to more than 3 GB of memory! What's gone wrong? Well, we used the strict version of foldl (indicated by the trailing tick '); BUT it's only strict up to "Weak Head Normal Form" (WHNF), which means it'll be strict in the structure of the tuple accumulator, but not the actual values!
As easy as any other programming language!
It is extremely hard to write high performance Haskell, same as it is hard to write high performance C. And additionally I think it is foolish to claim that "Haskell is no harder to learn than any languages". Definitely there are certain misconceptions (like you need to know category theory to learn Haskell) which needs to be debunked, but it is quite difficult to grasp the evaluation semantics of Haskell and pretending that it is easy and natural will simply shove more users away from the language.
I think it is easier to write clear, succinct code in Haskell and easier to write decently fast code in C. Neither is impossible in either.
Also, the previous article recommends newcomers to use the “Strict” language extension, which would avoid the exploding memory usage of the second version (“simple-fold-wc”).
On the contrary, in practice, it is important that the obvious code a programmer would write should be reasonably efficient (let's say, within an order of magnitude time and space of the optimal single-core solution). For this (very simple problem), this article makes it clear that is not true in Haskell. In contrast I believe it would be true in Rust and even Python (without having written the programs, but using BufReader::lines() and String::split() in Rust and the lines iterator and split() in Python).
It's also a problem for Haskell that the first thing you do for performance is to disable one of the key features that distinguishes Haskell from other languages.
With Haskell these things are possible, but not efficient by default (the default Haskell library uses liked lists instead of vectors for example).
Good news, there is indeed such a language: Fortran. Modern Fortran syntax is similar to Python (but without indentation restrictions) and the compiler generates wicked fast machine code.
Because Haskell is not just a language - it's a whole culture and by learning it you have to adopt that culture. That's the degree of mental shift you have to go through to really understand it.
Ultimately you don't become a Haskell programmer, but a Haskell person.
Is skiing even hard? Crawling -> Walking is arguably a lot harder.
Tell me that it isn't weird to write this https://en.wikipedia.org/wiki/Duff%27s_device
Tell me it isn't strange that array access is the same as pointer deref (aka a[index] is same as index[a])
It is very strange on first sight that a[index] is same as index[a], but you will never see the second one used in practice. When you are learning, you can write your code using normal array access syntax and solve problems. And then, you can learn to use pointers and deref them. And then one day you might realize that x[y] is *(x+y) and thus y[x] and that it looks funny. But that will be a long time after writing `wc`.
Duff's device is an abuse of an obscure syntax option nobody expected, and it's also seldom used.
Foldr, on the other hand, is bread and butter in Haskell.
>
Tell me it isn't strange that array access is the same as pointer deref (aka a[index] is same as index[a])*I can tell you, it isn't strange.
In other words, if a is char[]/char* and index is int, C does
*((char*)a + (int)index) and *((int)index + (char*)a)
and not as one could expect *((char*)a + (int)index) and *((int*)index + (char)a)
for a[index] and index[a] respectively.It shouldn't be this easy to shoot yourself in the foot when doing simple tasks
But maybe I am biased due to learning more about how computer implementations fundamentally operate (in which case the only surprising thing about a[b] == b[a] is that the C standard allows it) than FP theory and how that abstraction can be baked down into something that the computer can actually execute efficiently.
But most let you avoid them in favor of concepts manageable by an average middle schooler.
Today I saw somebody implementing C++'s std::is_integral in C# and the attempt to generate random values of generic type. It wasn't pretty, but stuff like this does not make C# a hard language.
Haskell is one of the simplest programming languages, but judging it by that statement is judging java for spring2 AbstractSingletonProxyFactory bean, ruby for all of rails monkey patching and magic, etc.
Stephen Diehl — Reflecting on Haskell in 2017
It could probably gain performance by playing around with input buffer sizes and trying to make use of vectorized instructions (the compiler might try to auto-vectorize the lops, but there is no guarantee).
[1] https://opensource.apple.com/source/text_cmds/text_cmds-68/w...
It does on my computer! The wc binary on my machine has movaps instructions.
Just a reminder that “orders of magnitude” means something specific, rather than “quite a bit”, and 3 is not “orders of magnitude” more than 0.3, and neither is 5.48 “orders of magnitude” more than 1.86
0.3 = 3 * 10^-1, which is -1 order of magnitude
3 = 0.3 * 10^1, which is 1 order of magnitude
You are right that 5.48 is not an order of magnitude more than 1.86, however. They are the same order of magnitude.
Of course you don't count 1: otherwise 3 would be 1 order of magnitude greater than 3, which is obviously wrong.
System wc, fastest of 5 runs:
59180000 213180000 1407437834 wc_input
11.53user 0.19system 0:11.74elapsed 99%CPU (0avgtext+0avgdata 2428maxresident)k
0inputs+0outputs (0major+102minor)pagefaults 0swaps
Manually compiled wc, fastest of 5 runs: 59180000 213180000 1407437834 wc_input
6.08user 0.20system 0:06.29elapsed 99%CPU (0avgtext+0avgdata 2180maxresident)k
0inputs+0outputs (0major+92minor)pagefaults 0swaps
This is on Ubuntu 18.04 on x86_64. If the author's wc also came precompiled (which it seems to be), they cannot make any valid comparison at all. If manually compiling on their machine with maximum optimization would also get them a 2x speedup, their fancy multicore Haskell would still be slower than C... and that's fine.That's not what I expected to read.
Although all of them are trying hard to be a little bit faster (and shorter) than C code, this is usually the price they have to pay:
1. Abysmal compilation time.
2. Huge binaries. Sure, C static binaries aren't small, but much smaller than equivalent Go programs.
3. Complex language. C is still simple language (sans edgy cases). No need to dive into type theory, learn about functors and so on just to write something.
4. Complex implementations (compilers, garbage collectors...). Not something you can hack over the weekend.
5. Complex distribution. C natural environment is Unix/Linux and libc/glibc is always there. Everything else requires additional (usually tons of) libraries or static linking.
6. Language instability. Because of 3), these languages are always evolving. You can read and compile C code 20-30 years ago and I'm expecting the same for the next, at least, 10 years.
Copyright (c) 1980, 1987, 1991, 1993
The Regents of the University of California. All rights reserved.I can say with confidence that the invariant will change exactly 0 times. No clue what the author is trying to say here.
> If you need to convert files from one markup format into another, pandoc is your swiss-army knife.
So, Pandoc does a lot of text processing.And the performance difference between idiomatic C code compiled with -O3 (to inline functions and minimize the stack twiddling and housekeeping code) and handwritten straightforward assembly is low enough as to be negligible. Not so with, say, Haskell vs C.
For example, ISPC[1] is a low-level language that is very similar to C, but which makes it straightforward for the compiler to use vector instructions very aggressively - far more than any existing C compiler would be able to.
A simple example is that pure functions can always be inlined and memoized.
In all respects, the only "esotetic" thing is the WHNF (which, if you worked with haskell for any while, is quite understandable).
he wrote the monoid directly, rather than import the library - and it's a rather unimportant small detail.
He didn't invent a new research topic that nobody has seen before. You would've implicitly done this same thing if you wrote a map/reduce algorithm to count words across different machines.
https://www.cs.purdue.edu/homes/bendy/Fiat/FiatByteString.ht...
The entire source for wc is here [0], and is 900 lines of very readable C, it does more than count words, includes options, arguments, usage, licenses. WHen I strip everything back, it's only about 300 lines of very readable C.
[0] https://github.com/coreutils/coreutils/blob/master/src/wc.c
>>> foldMap countChar "one two\nthree"
Counts {charCount = 13, wordCount = Flux NotSpace 3
NotSpace, lineCount = 1}”*
That lineCount = 1 surprised me, but testing on a Mac showed it to be ‘correct’. At least there, you can have a non-empty file that has zero lines.So a file that completely matches the string "one two\nthree" is by POSIX standards not a text file. Of course, wc doesn't necessarily operate on text files so you could interpret the result as a "complete POSIX line count".