11 ms·
Wc2: Investigates optimizing 'wc', the Unix word count program
- bruce343434 2y agoWhat about this is "asynchronous"?
- roelschroeven 2y agoI don't get that either. It feels like they compare the asynchronous-ness of their algorithm to Nginx being asynchronous ("asynchronous web-servers like Nginx use a state-machine parser. They parse the bytes as they arrive, and discard them."), but I don't see how that relates. The way web-servers handle requests (multiple threads vs multiple processes vs asynchronous event-driven in one thread) is completely orthogonal to how they parse headers. The impression I have is that their algorithm works in a streaming way, without having to allocate memory buffers, and that they call that asynchronous (wrongly, as far as I can see). I also don't really see what they mean by their algorithm being more scalable.
- laurent_du 2y agoMy understanding was that scalability came from the removal of memory buffers.
- stkdump 2y agoI guess since state is fully encoded inside a single state variable and of course the output counts, it would be trivially simple to switch between multiple input streams and incrementally count words in each of them as new data arrives.
- lesuorac 2y agoState machines are an underrated approached. Just remember, if you're ever debugging something and some values in a Class/Object/Group of them are set and others are unset the state machine avoids that issue. When you go to transition between states check that the future state will be valid and if-not go to an error state with that information. The amount of time I've seen spent debugging where spurious `null`s came from completely dwarfs the time it would've taken just to write that class/algorithm as a state machine. Kinda surprised WC wasn't a state machine to beginning with. Isn't it effectively a special characters counter where if you see a charactered followed by a space bump up the word count? I'm judging by the repos comment of "The real programs spend most of their time in functions like mbrtowc() to parse multi-byte characters and iswspace() to test if they are spaces -- which re-implementations of wc skip." that the big improvement is removing unnecessary work of those methods. mbrtowc [1] appears to re-create the provided substring which isn't necessary to count. [1]: https://en.cppreference.com/w/cpp/string/multibyte/mbrtowc https://en.cppreference.com/w/cpp/string/multibyte/mbrtowc
- munchler 2y ago> Just remember, if you're ever debugging something and some values in a Class/Object/Group of them are set and others are unset the state machine avoids that issue. Better yet, switch to a language that supports discriminated unions to avoid invalid state without having to write a low-level state machine. Each case in the union represents one of the valid states of the type. This is one of the many benefits of functional programming.
- tialaramex 2y agoThis comes down to "Make Invalid States Unrepresentable" Notably Go's choice here is instead "Make Representable States Valid". So for example in Go it's not possible for a type not to have a default value - every type must have a value you get by default, you could name this unwanted default value FUCK_OFF or DO_NOT_USE if you like, but in a larger system (where Go is supposed to thrive) you can be certain you'll find FUCK_OFF and DO_NOT_USE values in the wild. This is one of the few things the C++ type system almost gets right. You really can say for your C++ type no, it doesn't have a default. Unfortunately exception safety means we can easily end up in a place where too bad it's in some state anyway, but if we turn off exceptions or discount them we can live without nonsensical defaults.
- typon 2y agoMaybe something like CppFront can allow metaprogramming such that the default constructor is deleted by default on all types and becomes opt-in.
- ekidd 2y ago> This is one of the few things the C++ type system almost gets right. You really can say for your C++ type no, it doesn't have a default. Rust does even better here, I think, for fairly subtle reasons: - Exceptions are replaced by Result, with explicitly-marked return points. They're far less magic. ("panic!" is still magic, but it's allowed to be a call to "abort", so you only use it when the world is burning.) - "Move semantics" by default makes a lot of edge cases cleaner. If you move out of an object by default, it gets consumed, not set to a default value. Similarly, moving values into a newly-constructed object can't fail, because it's just memmove. - Object construction is atomic from the programmer's perspective. - Default initialization only works if you implement "Default". Which is actually just a normal trait with no magic. - If you discover that you have a state machine, you can switch to discriminated unions ("enum") to make your states mutually exclusive and clearly represented. This whole area is one of the better parts of Rust's design.
- im3w1l 2y agoI'm surprised there is no mention of simd. Like I'm sure this is "fast enough" but if you want to make a really fast wc for fun wouldn't that be a natural direction?
- thequux 2y agoA hand-written SIMD wc is likely to be even faster than a state machine, but at the cost of orders of magnitude more work. The huge advantage of state machines are that they are a relatively generic approach that provides massive speedups nearly every time. A SIMD wc algorithm is a significant effort that can't be generalized, and is only likely to provide a 4x speedup or so: rarely worth it except in cases where the task is a performance hotspot for a lot of applications.
- Joker_vD 2y agoSIMD-based reimplementations of wc already exist, e.g. this [0] one, and it's rather straightforward. [0] https://github.com/expr-fi/fastlwc https://github.com/expr-fi/fastlwc
- mananaysiempre 2y agoAn ASCII SIMD wc would likely be much more than 4× faster. The 320 MB/s is speed TFA quotes is good for a byte-at-a-time solution, but pitiful as far as the capabilities of modern machines are concerned. A decent SSD is an order of magnitude faster than that. Around 1 GB/s (i.e. ~100 cycles/fetch) is table stakes for a task of this complexity. (TFA almost nerd-sniped me into writing a SIMD implementation already, and you finished the job. End result: on an aging 2.5 GHz Broadwell, I’m seeing 300 MB/s for TFA’s C implementation and 3200 MB/s for my first attempt at an x86-64-v3 one. So more like a 10× speedup, and its highly likely one can do better. Admittedly I did spend around an hour on these 50 lines, and would need to spend more in reality to check for CPU features at runtime and so on.) However, TFA calls going ASCII-only “cheating”, and I can see its point. I don’t know how difficult a Unicode SIMD wc would be or if it’s even possible to do well. (Bonus points: do you want to define a word boundary as a space/nonspace boundary the way[1] POSIX tells you to, or the more complex way[2] Unicode tells you to?) [1] https://pubs.opengroup.org/onlinepubs/9699919799/utilities/wc.html https://pubs.opengroup.org/onlinepubs/9699919799/utilities/w... [2] https://www.unicode.org/reports/tr29/#Word_Boundaries https://www.unicode.org/reports/tr29/#Word_Boundaries
- mjamil 2y ago"Many programmers think pointer-arithmetic is faster." Don't modern compilers make this statement false (i.e., both approaches are implemented via the same machine instructions)?
- IshKebab 2y agoThey definitely do in simple cases (e.g. a simple for loop). In more complex cases, especially when the index/pointer escapes a function then the code will be different.
- jimbobthrowawy 2y agoI checked using godbolt, and when compiling with -O2 (like his makefile) only the parse_chunk_pp version is in the emitted assembly and is called regardless of the -P option. I think compilers have done this where applicable for a long time. Compiling without any arguments leads to two lines differing in the assembly for the functions.
- trealira 2y agoSomething funny is that GCC may compile your code that uses pointer arithmetic into one that uses an index register, and compile your code that uses an index into an array as pointer arithmetic. https://godbolt.org/z/9KPnnM7Po https://godbolt.org/z/9KPnnM7Po
- markstos 2y agoWas this ever submitted an update to the `wc` shipped on systems?
- canucker2016 2y agoI doubt it - from the project's readme page: "...Now the real wc works with a lot more character-sets, and we don't do that. But by implementing UTF-8, we've shown that it's possible, and that the speed for any character-set is the same." Looking at the command line options for wc2.c and comparing to the FSF wc man page, it looks like there are some missing/unsupported options in wc2.c as well.
- anon1040 2y ago> ...the real wc works with a lot more character-sets... This should read: the real wc works with a lot more character _encodings_
- YesThatTom2 2y agoI love state machines and every time I use one my workers think I invented it because they’ve never seen them before. The data for state machine in this article might be best prepared by generating it from a program. That generator program doesn’t need to care (too much) about performance since it is run during the build process. I like the idea of doing a lot of work now to save time in the future.
- pletnes 2y agoDo you have any accessible references on state machines? I’ve just read about them a bit but never coded one in a project. Seems like a useful concept for testable, reliable code.
- GrantMoyer 2y agoThe video Finite State Machines explained by Abelardo Pardo[1] seems like a good introduction (I'm not familiar with the author; I just searched Finite State machine on youtube and found the first result which wasn't a jumbled mess of abstract or misused jargon). It may seem simple, but that's truely all there is to finite state machines, a set of finite states and a set of events which cause transitions between states. Their specific applications to various domains is a much larger topic, but with a basic understanding, any application should be clear whenever it comes up. There's no one way to implement a state machine, and you've probably used them all the time, even if you haven't thought about them formally. For example, a simple but common 2-state machine takes the form: running = true while running: … if <some condition>: running = false [1]: https://www.youtube.com/watch?v=hJIST1cEf6A https://www.youtube.com/watch?v=hJIST1cEf6A
- d0mine 2y agoIt could be written as: while True: ... if <exit condition>: break
- trealira 2y agoA finite state machine has a set of input symbols, a set of states, and a transition function, which maps the current state and current input to the next state (and, when programming it, it doesn't have to be a literal function; for example, it could be a 2D array). It also has a start state, and a set of accept states. It's also common for state machines to have some sort of output; otherwise, all an FSM can do is recognize whether an input string is "good." So, there's also an output function, so that the FSM actually does something while processing the input string. There are two types of FSMs: a Mealy Machine, and a Moore machine. In a Mealy machine, the output function maps the current state and the current input to an output; so, one state could be associated with multiple outputs. In a Moore machine, the output is purely a function of the current state, no matter the input. Usually, a Moore machine has more states than the equivalent Mealy machine. In practice, Moore machines are a lot rarer than Mealy machines. You can model FSMs in a variety of ways. You could use the state pattern [0]. You could have a table-based state machine; examples in C here [1] [2]. It's also common to model them using a loop and a switch statement with integers to represent the current state - or just use "goto" to go to the next state, if it's available in your language. Also, this is tangential, but something nice about coroutines is that they save can you from writing an explicit state machine, as the state is implicit in your code. One example of this is how it's easier to write iterators as coroutines that yield results as they run, rather than as structures that update themselves based on their current state, transition to the next state, and yield a result. So far, what I've covered is basically a deterministic finite automaton (DFA). There are also non-deterministic finite automata (NDFAs), which are used to implement regular expressions (at least when regular expressions aren't extended to require more powerful recognizers) [3], as well as pushdown automata (PDAs), which are basically finite automata with a stack, and can parse e.g. programming languages. Finally, there are Turing machines. For theory on that, I'd recommend reading Sipser's Introduction to the Theory of Computation. If you look up the book on Google, it's not difficult to find a PDF of it. [0]: https://refactoring.guru/design-patterns/state https://refactoring.guru/design-patterns/state [1]: https://nullprogram.com/blog/2020/12/31 https://nullprogram.com/blog/2020/12/31 [2]: https://ideone.com/94U6aJ https://ideone.com/94U6aJ (this one removes C-style comments from source code - I didn't make it) [3]: https://swtch.com/~rsc/regexp/regexp1.html https://swtch.com/~rsc/regexp/regexp1.html
- jmholla 2y ago> No, you aren't suppose to be able to see how the word-count works by looking at this code. The complexity happens elsewhere, setting up the state-machine. This is like most of the reason I opened this article. I wish they'd spend more time talking about this. In fact, most of the README covers details that are important, but, irrelevant to their algorithmic improvements. Maybe they expect you to open up the code, but even there the comments are largely describing what things do and not why, so I feel you need to have some understanding of the algorithm in question. For example, the parts where the state table gets constructed rather unhelpful comments to the uninformed: /** * Build an ASCII row. This configures low-order 7-bits, which should * be roughly the same for all states */ static void build_basic(unsigned char *row, unsigned char default_state, unsigned char ubase) ... /** * This function compiles a DFA-style state-machine for parsing UTF-8 * variable-length byte sequences. */ static void compile_utf8_statemachine(int is_multibyte) Even `wc2o.c` doesn't delve into the magic numbers it has chosen. I was hoping this repo would be more educational and explain how the state table works and why it's constructed the way it is. Does anyone have a good resource for learning more about asynchronous state-machine parsers, that also could hopefully help explain why this is better than just iterating over characters? I'm guessing maybe it's the lack of branching?
- VMG 2y agoI think the documentation might be stale, `build_basic` clearly has code for non-ASCII characters
- thechao 2y agoI’m with you. It appears to be a fairly bog-standard DFA, but divining that from 4x4 `int`s and a 256 `char` array feels like I’d just be doing all of the heavy lifting, intellectually. However… it does look like it’s trying to detect spaces (that’s the array of 256 `char`, as `char` is self-indexing). I can’t be bothered to remember how `wc` works, but my guess is that the state-machine has transition states for `sp->sp`, `sp->wd`, `wd->wd`, and `wd-sp`. It’d also need error modes. I suppose it doesn’t contain states for escapes?
- zadokshi 2y ago
- rakoo 2y ago> This state machine approach always results in the same speed, regardless of input. This is strange to me, shouldn't it be O(N) with the size of the input ? Or maybe in this benchmark the inputs are small enough that the difference isn't measurable ?
- VMG 2y agohe is talking in context of same-sized files (counted in bytes)
- sebastianmestre 2y agoThey meant that different characters don't change the performance, unlike the Linux and MacOS versions, where different characters go through different code paths. But yes, a bigger file does take longer to process.
- roywiggins 2y agoSpeed as in bytes per second, regardless of which bytes you give it.
- fsckboy 2y agowhile you are in there, wc --unicode wc --bom
- aargh_aargh 2y agoI wanted to take a peek the state diagram (ASCII version). But I was feeling lazy, so apologies for having ChatGPT do the work for me. I wasn't going for correctness and didn't check it. If you're like me, here you go: https://dreampuf.github.io/GraphvizOnline/#digraph%20StateMachine%20%7B%0A%20%20%20%20rankdir%3DLR%3B%0A%20%20%20%20size%3D%228%2C5%22%3B%0A%20%20%20%20node%20%5Bshape%20%3D%20circle%5D%3B%0A%20%20%20%20%0A%20%20%20%20LookingForWord%20-%3E%20InsideWord%20%5Blabel%3D%22Non-space%22%5D%3B%0A%20%20%20%20LookingForWord%20-%3E%20LookingForWord%20%5Blabel%3D%22Space%22%5D%3B%0A%20%20%20%20LookingForWord%20-%3E%20Newline%20%5Blabel%3D%22Newline%22%5D%3B%0A%20%20%20%20LookingForWord%20-%3E%20LookingForWord%20%5Blabel%3D%22Other%22%5D%3B%0A%20%20%20%20%0A%20%20%20%20Newline%20-%3E%20InsideWord%20%5Blabel%3D%22Non-space%22%5D%3B%0A%20%20%20%20Newline%20-%3E%20LookingForWord%20%5Blabel%3D%22Space%22%5D%3B%0A%20%20%20%20Newline%20-%3E%20Newline%20%5Blabel%3D%22Newline%22%5D%3B%0A%20%20%20%20Newline%20-%3E%20LookingForWord%20%5Blabel%3D%22Other%22%5D%3B%0A%20%20%20%20%0A%20%20%20%20InsideWord%20-%3E%20ContinueWord%20%5Blabel%3D%22Non-space%22%5D%3B%0A%20%20%20%20InsideWord%20-%3E%20LookingForWord%20%5Blabel%3D%22Space%22%5D%3B%0A%20%20%20%20InsideWord%20-%3E%20Newline%20%5Blabel%3D%22Newline%22%5D%3B%0A%20%20%20%20InsideWord%20-%3E%20LookingForWord%20%5Blabel%3D%22Other%22%5D%3B%0A%20%20%20%20%0A%20%20%20%20ContinueWord%20-%3E%20ContinueWord%20%5Blabel%3D%22Non-space%22%5D%3B%0A%20%20%20%20ContinueWord%20-%3E%20LookingForWord%20%5Blabel%3D%22Space%22%5D%3B%0A%20%20%20%20ContinueWord%20-%3E%20Newline%20%5Blabel%3D%22Newline%22%5D%3B%0A%20%20%20%20ContinueWord%20-%3E%20LookingForWord%20%5Blabel%3D%22Other%22%5D%3B%0A%7D%0A https://dreampuf.github.io/GraphvizOnline/#digraph%20StateMa... digraph StateMachine { rankdir=LR; size="8,5"; node [shape = circle]; LookingForWord -> InsideWord [label="Non-space"]; LookingForWord -> LookingForWord [label="Space"]; LookingForWord -> Newline [label="Newline"]; LookingForWord -> LookingForWord [label="Other"]; Newline -> InsideWord [label="Non-space"]; Newline -> LookingForWord [label="Space"]; Newline -> Newline [label="Newline"]; Newline -> LookingForWord [label="Other"]; InsideWord -> ContinueWord [label="Non-space"]; InsideWord -> LookingForWord [label="Space"]; InsideWord -> Newline [label="Newline"]; InsideWord -> LookingForWord [label="Other"]; ContinueWord -> ContinueWord [label="Non-space"]; ContinueWord -> LookingForWord [label="Space"]; ContinueWord -> Newline [label="Newline"]; ContinueWord -> LookingForWord [label="Other"]; } EDIT: Under peer pressure, I checked it and it correctly reflects the code apart from being designed for one specific line ending sequence (as it should, being an example optimized for brevity). As for the replies, as opposed to my approach, I'm sure when you're browsing research papers, you're doing a full reproducibility study for each one. I'm sorry I commented, I should have waited for you to post your results.
- mananaysiempre 2y ago> This is analogous to NFA and DFA regular-expressions. If you use the NFA approach, you need to buffer the entire chunk of data, so that the regex can backtrack. Using the DFA approach, input can be provided as a stream Sorry, no, this is completely wrong. There are other reasons NFAs or DFAs might be preferable, and there are other performance considerations as far as backtracking is concerned, but NFA implementations do not backtrack. I mean, they could, but they don’t, and in common usage a “NFA regex implementation” means a non-backtracking one (that goes through all input once with a bag of states in hand and advances each one of them on each step), whereas a “backtracking regex implementation” means one that doesn’t use automata at all (and is usually worst-case exponential in the input). What this is actually talking about is a streaming parser. Just call it like it is, it’s an OK term that sees plenty of usage. [What you could mention here is PEG parsers, because even linear PEG implementations may need to keep O(input) state and thus are essentially incapable of streaming, unlike LL or LR ones; and GLR et al. can be even worse, for what it’s worth. But this is a much more obscure topic.]
- veltas 2y agoHow do you implement a non-backtracking NFA other than converting it to a DFA?
- burntsushi 2y agoAt search time, the principle difference between an NFA and a DFA is that, in an NFA, you can be in more than one state at the same time. There's no problem with implementing your transition function to advance all states you are in simultaneously for each character of input. You'll get `O(m * n)` time, where `m` is proportional to the number of states in the NFA and `n` is proportional to the length of the input. The GP is remarking on a confusable term, "NFA algorithm," that has come to mean something different from its underlying theory. The PCRE2 documentation itself, for example[1], remarks about how it uses the "NFA algorithm" as its standard approach to matching. But of course, PCRE2 supports way more than the theoretical model of non-deterministic finite automata (NFA) actually supports. PCRE2 is much more expressive. Yet, the implementation approach is still called "NFA algorithm." Presumably the reason for this is that an NFA can be simulated by doing backtracking, but if you don't keep track of where you've visited, the worst case runtime of this is superlinear, possibly catastrophically so[2]. The problem is that the backtracking regex engines have evolved well beyond what an NFA actually supports. But the name stuck. To make things even more confusing, as I mentioned above, an NFA can be used to execute a search in O(m * n) time. (We typically call that "linear in the size of the input" since the NFA itself can usually, but not always, be regarded as a constant factor. i.e., A literal regex string in your program source code.) So when you say something like, "a finite automata regex engine uses NFAs to guarantee linear time," you might be really confused if your background is in backtracking engines which... also use an "NFA," but of course cannot guarantee linear search time. So what we have is ambiguous terminology, not unlike "regex" itself, which could perhaps mean a real theoretical "regular expression" (in the case of Hyperscan, RE2, Go's regexp package and Rust's regex crate) or it could mean "a very expressive DSL for pattern matching that supports more than what regular languages can describe" (in the case of PCRE2, ECMAScript's regex engine, Ruby's Oniguruma, Python's `re` module, and more). I've made my peace with "regex" being ambiguous, but the fact that "NFA algorithm" is itself ambiguous despite "non-deterministic finite automata" being a somewhat baroque and specific technical term, is very unfortunate. To make things even worse---and I shit you not, I am not joking---the backtracking people seem to have taken to calling a linear time NFA search the "DFA algorithm."[3] (At least the PCRE2 docs mention it's not a "traditional" finite state machine...) But... it's not a DFA. The backtracking folks have effectively elevated the terms "NFA" and "DFA" to mean something very different from their theoretical underpinnings. So when you have people that are only aware of one meaning of "NFA algorithm" talking to other people only aware of the other meaning of "NFA algorithm," chaos ensues. [1]: https://www.pcre.org/current/doc/html/pcre2matching.html https://www.pcre.org/current/doc/html/pcre2matching.html [2]: https://github.com/BurntSushi/rebar?tab=readme-ov-file#cloud-flare-redos https://github.com/BurntSushi/rebar?tab=readme-ov-file#cloud... [3]: https://www.pcre.org/current/doc/html/pcre2matching.html#TOC1 https://www.pcre.org/current/doc/html/pcre2matching.html#TOC...
- smaudet 2y agoI was a bit surprised by the macos/linux speed differential here: > The difference in macOS and Linux speed is actually the difference in clang and gcc speed. The LLVM clang compiler is doing better optimizations for x86 processors here. I know GCC has been getting much, much more aggressive as of late, but there have been some complaints that it is now much, much less safe (checks intended for security getting optimized away, e.g.). I wonder if you were to go back to 5 years ago, if you'd see the linux code was generally safer than the speedy osx llvm code...
- aftbit 2y agoIt would have been nice for the author to label the states and explain how and why they chose the states that they did. Otherwise, it's hard to understand how to apply this sort of thing to larger problems.
- jxndnxu 2y agoHow would if have helped? You either design a DFA by hand or use a compiled from a regular language
- cryptos 2y agoNow we need another round of the language battle, because now this approach needs to be implemented in Rust, Go, Zig, Nim ... you name it!
- rep_movsd 2y agoRemember "The Zen of Code Optimization" by Michael Abrash in the 90s? This word count challenge was the first one he described. The table driven approach was discussed, but was not necessarily the fastest due to the large cache overflowing (on 90s processors) table needed. I used the same example in a chapter I wrote for a C++ book
- moody__ 2y agoThe "asynchronous state machine" name here is a bit strange, when searching for this term used elsewhere I couldn't find any formal definition what it is. Reading further in the README it looks like the author implies that it really just means a DFA? Not entirely sure. I'd also like to add the Plan 9 implementation[0], which also uses the properties of utf8 as part of its state machine and anecdotally has been quite performant when I've used it. [0] http://git.9front.org/plan9front/plan9front/107a7ba9717429ae34294d9afa804b5271157ab0/sys/src/cmd/wc.c/f.html http://git.9front.org/plan9front/plan9front/107a7ba9717429ae...
- rhelz 2y ago"Asynchronous" isn't part of the name of some really cool state machine :-) Its just an adjective and means the same as when you put it in front of any other noun. A synchronous state machine is one where the incoming stream of events is always "in sync" with the state transitions, in the following sense: 1. When an event happens, the state machine can transition to the next state and perform any necessary actions before the next event happens 2. After the the state machine has transitioned and performed any necessary actions, the program must wait for the next event to happen. It can't do anything else until it does. An asynchronous state machine doesn't make the main program wait until the next event happens. It can go on and do other things in the meantime. It doesn't have to wait for then next event to arrive. When the next event does arrive, the program pauses whatever else it is doing, and hands control back to the state machine, which process the event, and then hands control back over to the main program.
- PaulHoule 2y agoAs I see it, state machines are particularly good for expressing logic in asynchronous systems. For instance in the late 1980s I wrote assembly language XMODEM implementations for the 6809 and the 80286 and since that kind of code is interrupt drive it is efficient to make a state machine that processes one character at a time. Today when you use async/await the compiler converts your code, loops and all, into a state machine.
- 2y ago
- JonChesterfield 2y agoRecognising that wc is a lexer problem and implementing it using re2c would be my first choice here. That'll be building a similar state machine to what is done by hand here, especially since the hand rolled one is still byte at a time (the main drawback to re2c's generated output).
- GrantMoyer 2y ago> The algorithm is known as an "asynchronous state-machine parser". It's a technique for parsing that you don't learn in college. The mapping from regular and context free languages to state machines and their table-based implementations was covered in depth in the Compilers course I took. A table based state machine is literally the textbook algorithm for parsing these classes of languages, and implementing them has been almost entirely automated by tools like Flex and Bison since the 80s.
- mcguire 2y agoFor example, see Chapter 3 of the Dragon Book, Compilers: Principles, Techniques, and Tools by Aho, Ullman, et al. Or probably any other compilers text book.
- mywittyname 2y agoCompilers was a graduate course at my school. CS as a field has grown quite a lot over the years, and it seems that colleges are responding by pushing the more theoretical classes into grad school to make room for the more applied classes.
- throwaway55533 2y agoFrom reading the article, how is this more efficient? Doesn't any word counting algorithm have to iterate through all the characters and count spaces? What makes this better than the standard algorithm of wc = 0 prev = null for ch in charStream: if !isSpace(ch) and isSpace(prev): wc += 1 prev = ch
- GrantMoyer 2y agoBasically, it's just a lookup table for isSpace, rather than whatever logic is in the original function (which probably has conditional branches). There's a little bit of a complication in the fact that a state machine can implicitly share parts of the computation for utf-8 encoded codepoints with shared prefixes, so instead of a 2^32-element lookup table, you only need 4 2^8-element lookup tables (and instead of 1 state, parsing codepoint, you have 4, parsing first byte, parsing second byte, etc.).
- throwaway55533 2y agoAh. Is 8 bits really optimal? I don't know how many UTF space characters there are, I thought there were only a few. Why not a 16-bit lookup?
- GrantMoyer 2y agoUTF-8 encoded codepoints can have an odd number of bytes, so processing a file 2 bytes at a time would be a little more complicated. Processing the file one codepoint at a time works because you can decode the UTF-8 stream into a stream of 32-bit codepoints before passing the codepoints to the lookup table. I suppose you could also transform from UTF-8 to UTF-16 before passing values to the lookup table. Processing byte by byte isn't necessarily faster than processing codepoint by codepoint, or any other size. You'd need to measure performance empirically, and it probably depends on caches sizes and other factors. In theory, you could also process bit by bit — then you'd only need 32 2-element lookup tables — but that's unlikely to be efficient, since you'd need to do a lot of bit manipulation. Edit: Upon inspection, the method I described doesn't appear to be the method used by the featured program. It still basically uses a lookup table for detecting space characters, byte by byte, but the states are not how I described. Instead of the states representing which byte of a UTF-8 encoded codepoint is being processed, and the word count being incremented upon certain transitions — a Mealy machine — the state represent the class of the codepoint last fully processed, and the count is always increased based on the current state (often by zero) — a Moore machine.
- JackSlateur 2y agoReading the code to help me understand how things are I got the wc_lines from coreutils: https://github.com/coreutils/coreutils/blob/master/src/wc.c#L248 https://github.com/coreutils/coreutils/blob/master/src/wc.c#... And I thought "damn, I understand nothing about the state-machine stuff, how did they made this faster ?" Truth is: they did not Of course, this is just the "count line" part. Other parts are indeed faster. Coreutils 9.4: 0.67 [jack:/tmp] /usr/bin/time -v wc -l debian-12.2.0-amd64-netinst.iso 2524855 debian-12.2.0-amd64-netinst.iso Command being timed: "wc -l debian-12.2.0-amd64-netinst.iso" User time (seconds): 0.00 System time (seconds): 0.07 Percent of CPU this job got: 98% Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.07 Average shared text size (kbytes): 0 Average unshared data size (kbytes): 0 Average stack size (kbytes): 0 Average total size (kbytes): 0 Maximum resident set size (kbytes): 2176 Average resident set size (kbytes): 0 Major (requiring I/O) page faults: 0 Minor (reclaiming a frame) page faults: 99 Voluntary context switches: 1 Involuntary context switches: 0 Swaps: 0 File system inputs: 0 File system outputs: 0 Socket messages sent: 0 Socket messages received: 0 Signals delivered: 0 Page size (bytes): 4096 Exit status: 0 And wc2 (from gcc -O3 -o wc2 wc2.c): 0.47 [jack:/tmp] /usr/bin/time -v ./wc2 -l debian-12.2.0-amd64-netinst.iso 2524855 debian-12.2.0-amd64-netinst.iso Command being timed: "./wc2 -l debian-12.2.0-amd64- netinst.iso" User time (seconds): 0.97 System time (seconds): 0.05 Percent of CPU this job got: 99% Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.03 Average shared text size (kbytes): 0 Average unshared data size (kbytes): 0 Average stack size (kbytes): 0 Average total size (kbytes): 0 Maximum resident set size (kbytes): 2176 Average resident set size (kbytes): 0 Major (requiring I/O) page faults: 0 Minor (reclaiming a frame) page faults: 146 Voluntary context switches: 1 Involuntary context switches: 1 Swaps: 0 File system inputs: 0 File system outputs: 0 Socket messages sent: 0 Socket messages received: 0 Signals delivered: 0 Page size (bytes): 4096 Exit status: 0 Gotta keep reading
- orf 2y agoAny notable difference if you pipe the file in, rather than read from disk? IO caches are a thing as well, don’t use the first measurement.
- JackSlateur 2y ago
- deleted 2y ago[deleted]
- NunoSempere 2y agoFrom a previous project: https://nunosempere.com/blog/2023/09/15/wc/ https://nunosempere.com/blog/2023/09/15/wc/ that was looking not at speed, but at simplicity, here is a comparison of different historical versions of wc: --- The [version of wc.c](https://git.nunosempere.com/personal/wc/src/branch/master/src/wc.c https://git.nunosempere.com/personal/wc/src/branch/master/sr...) in this repository sits at 44 lines. It decides to read from stdin if the number of arguments fed to it is otherwise zero, and uses the standard C function getc to read character by character. It doesn't have flags, instead, there are further utilities in the src/extra/ folder for counting characters and lines, sitting at 32 and 35 lines of code, respectively. This version also has little error checking. [Here](https://github.com/dspinellis/unix-history-repo/blob/Research-V7-Snapshot-Development/usr/src/cmd/wc.c https://github.com/dspinellis/unix-history-repo/blob/Researc...) is a version of wc from UNIX V7, at 86 lines. It allows for counting characters, words and lines. I couldn't find a version in UNIX V6, so I'm guessing this is one of the earliest versions of this program. It decides to read from stdin if the number of arguments fed to it is zero, and reads character by character using the standard C getc function. The busybox version ([git.busybox.net](https://git.busybox.net/busybox/tree/coreutils/wc.c https://git.busybox.net/busybox/tree/coreutils/wc.c)) of wc sits at 257 lines (162 with comments stripped), while striving to be [POSIX-compliant](https://pubs.opengroup.org/onlinepubs/9699919799/ https://pubs.opengroup.org/onlinepubs/9699919799/), meaning it has a fair number of flags and a bit of complexity. It reads character by character by using the standard getc function, and decides to read from stdin or not using its own fopen_or_warn_stdin function. It uses two GOTOs to get around, and has some incomplete Unicode support. The [plan9](https://9p.io/sources/plan9/sys/src/cmd/wc.c https://9p.io/sources/plan9/sys/src/cmd/wc.c) version implements some sort of table method in 331 lines. It uses plan9 rather than Unix libraries and methods, and seems to read from stdin if the number of args is 0. The plan9port version of wc ([github](https://github.com/9fans/plan9port/blob/master/src/cmd/wc.c https://github.com/9fans/plan9port/blob/master/src/cmd/wc.c)) also implements some sort of table method, in 352 lines. It reads from stdin if the number of args is 0, and uses the Linux read function to read character by character. The [OpenBSD](https://github.com/openbsd/src/blob/master/usr.bin/wc/wc.c https://github.com/openbsd/src/blob/master/usr.bin/wc/wc.c) version is just *nice*. It reads from stdin by default, and uses a bit of buffering using read to speed things up. It defaults to using fstat when counting characters. It is generally pleasantly understandable, nice to read. I'm actually surprised at how pleasant it is to read. The [FreeBSD version](https://cgit.freebsd.org/src/tree/usr.bin/wc/wc.c https://cgit.freebsd.org/src/tree/usr.bin/wc/wc.c) sits at 367 lines. It has enough new things that I can't parse all that it's doing: in lines 137-143, what is capabilities mode? what is casper?, but otherwise it decides whether to read from stdin by the number of arguments, in line 157. It uses a combination of fstat and read, depending on the type of file. Finally, the GNU utils version ([github](https://github.com/coreutils/coreutils/tree/master/src/wc.c https://github.com/coreutils/coreutils/tree/master/src/wc.c), [savannah](http://git.savannah.gnu.org/gitweb/?p=coreutils.git;a=blob;f=src/wc.c;hb=HEAD http://git.savannah.gnu.org/gitweb/?p=coreutils.git;a=blob;f...)) is a bit over 1K lines of C. It does many things and checks many possible failure modes. I think it detects whether it should be reading from stdin using some very wrapped fstat, and it reads character by character using its own custom function. So this utility started out reasonably small, then started getting more and more complex. [The POSIX committee](https://pubs.opengroup.org/onlinepubs/9699919799/ https://pubs.opengroup.org/onlinepubs/9699919799/) ended up codifying that complexity, and now we are stuck with it because even implementations like busybox which strive to be quite small try to keep to POSIX.
- btown 2y agoState machines are great for complex situations, but when it comes to performance, it's not at all clear to me that they're the most scalable approach with modern systems. The data dependency between a loop iteration for each character might be pipelined really well when executed, and we can assume large enough L1/L2 cache for our lookup tables. But we're still using at least one lookup per character. Projects like https://github.com/simdjson/simdjson?tab=readme-ov-file#about-simdjson https://github.com/simdjson/simdjson?tab=readme-ov-file#abou... are truly fascinating, because they're based on SIMD instructions that can process 64 or more bytes with a single instruction. Very much worth checking out the papers at that link.
- jxndnxu 2y agoMy understanding of the article's use of scalable was "fixed overhead more or less regardless of the complexity of the state machine and input" not "fastest implementation available"
- ashvardanian 2y agoIn the context of State Machines and Automatas - Intel HyperScan might be a better reference point. But the idea is the same. With a trivial PoC using Python wrappers over SIMD libraries one can get a 3x boost over the native `wc` CLI on a modern CPU, memory-mapping a very average SSD: https://github.com/ashvardanian/StringZilla/tree/main/cli https://github.com/ashvardanian/StringZilla/tree/main/cli
- teo_zero 2y agoSorry, but your wc implementation does nothing to detect words, it just counts the spaces. Of course you don't need a state machine for that!
- apitman 2y agoI didn't know you were allowed to use a language other than Rust for something like this.
- nitwit005 2y agoThe primary reason their code is faster as they've made incorrect code that assumes you always have a UTF-8 locale. The normal isspace does not assume this: > The real programs spend most of their time in functions like mbrtowc() to parse multi-byte characters and iswspace() to test if they are spaces This will produce bad results in the real world. People have previously posted about bugs related to this on Hacker News: https://news.ycombinator.com/item?id=36216389 https://news.ycombinator.com/item?id=36216389
- scottlamb 2y agoAre we looking at the same thread? Folks there seem to be complaining the old interfaces are anything from outdated to confusing to simply wrong, and I agree. I think it's totally reasonable for a program designed in 2024 to say it only supports ASCII and UTF-8 encodings. Whether/how it should support the full spectrum of Unicode definitions of characters/graphemes/... is more interesting. For a lot of backend code (processing text-based network protocols, for example), focusing on ASCII is arguably best (e.g. functions like isspace and isdigit only returning true for ASCII characters). For more user-focused stuff, most of the world would say they'd like their native language supported well. Programs written with both use cases in mind should probably have a switch. (Or parallel APIs: e.g. Rust has {u8,char}::is_ascii_digit vs. char::is_numeric, which makes much more sense there than having one that switches behaviors based on an environment variable, as the correct behavior really depends on the call site.) Of course "say it only supports ASCII and UTF-8 encodings" is mutually exclusive with claiming to be a drop-in replacement for a utility that is specified as having POSIX locale support. This project does not make that claim, or even that it's intended to be actually used rather than illustrative of a performance technique.
- zzo38computer 2y ago> I think it's totally reasonable for a program designed in 2024 to say it only supports ASCII and UTF-8 encodings. I think that it should depends on the program; that might be reasonable for some programs but in a lot of cases I think that it won't be reasonable. (Your explanation includes some of the examples, although not all of them.) Sometimes, it is most helpful to support only ASCII (although non-ASCII bytes might still be supported, even without needing special processing to handle them; in some cases this may effectively allow other ASCII-compatible encodings as well such as EUC-JP). Sometimes, a program should not need to deal with character encoding at all. Sometimes, it makes sense to deal with whatever character encodings are used in the file formats the program is designed to handle. Sometimes, it makes sense to support multiple character encodings, with or without conversion (depending on what is being done with them). Even if a program does only support ASCII and UTF-8 encodings, then depending on what it does with them, mentioning ASCII might be unnecessary since UTF-8 is a superset of ASCII anyways. But unfortunately many programs use UTF-8 (or other encodings, but mostly UTF-8) where it is inappropriate to do so, which can result in many problems including inefficiency.
- 1vuio0pswjnm7 2y ago"The wc program included with macOS and Linux are completely different. Therefore, the following table shows them benchmarked against each other on the same hardware." Appears BSD wc ("the macOS program") is much faster than the GNU coreutils wc ("the Linux program"). It certainly illustrates a point about people rewriting wc in newer languages to demonstrate alleged speed against C. Which wc are they using for comparison. Pehaps they should use wc2 or wc2o.
- mytec 2y agoThat's a really good point. I'm using macOS and I tested -w option against a CSV file that is about 430MB in size and has about 18,000,000 words in it. The time was 0.989. When I ran wc2 on the same file, it clocked in at 0.943. I wondered what I was doing wrong and came back to the comments section and found your comment. Ah. Edit: interestingly, the newline count time was 0.458 with the macOS version and 0.943 with wc2.
- kristianpaul 2y agoIsn't fedora working on improving some gnu tools?
- fragmede 2y agoIn the bringing a tank to a knife fight kind of way, could this be optimized to run on a GPU? Load the contents then do an "and" across the whole contents in parallel, and then sum the whitespaces?
- Dylan16807 2y agoThese benchmarks are on 92 million byte files so we're into the range where bringing a tank is fair (and worth the startup cost).
- stkdump 2y agoI doubt that you can make it faster on the GPU than on CPU when utilizing SIMD, reason being that you are actually doing something close to trivial upon looking at each byte in sequence. So you transfer it from CPU memory to GPU memory in order to do almost nothing with it.
- Dylan16807 2y agoIt's only at a limit like that if you don't parallelize. And sure you could use more cores, but you can go a lot faster on 20% of a GPU than on 20% of your CPU cores.
- fragmede 2y agoI've got it working on a T4 via Google Colab. The PDF takes 178 milliseconds to the 206 listed in the readme for the C version, so 15%? https://github.com/fragmede/wc-gpu/blob/main/wc_gpu.ipynb https://github.com/fragmede/wc-gpu/blob/main/wc_gpu.ipynb
- fragmede 2y agoI got nerd sniped into doing it. https://github.com/fragmede/wc-gpu https://github.com/fragmede/wc-gpu
- Maro 2y agoI wrote a clean C++ version of `wc` for fun, and successfully beat the system version by 10-20% iirc. My goal was to make the code much more readable than the GNU/C version, which is a big spaghetti loop, while maintaining the same semantics (ie. return the same counts). Blog posts: https://bytepawn.com/tag/wc.html https://bytepawn.com/tag/wc.html Code: https://github.com/mtrencseni/wcpp/ https://github.com/mtrencseni/wcpp/
- butterisgood 2y agoA "word" counter in C++ (not really, but kind of) std::cout << std::distance(std::istream_iterator<std::string>(std::cin), std::istream_iterator<std:::string>()) << std::endl; And I guess you could get "character" count using istreambuf_iterator. Don't do this :-) (Though I've used it in a pinch)
- butterisgood 2y agoAlso, sorry for the typos... the character version is istreambuf_iterator<char> also... whoops!
- kazinator 2y agoThe target audience, Unix graybeards programming shell scripts using commands like wc, is extremely hard to convince to use new tools. If you don't integrate these optimizations into, say, the GNU Core Utils wc program, the impact will be nil.
- nikau 2y agoGood to see effort to speed up wc, its been taking way too many cycles away from my 1.5GiB electron chat program
- 1vuio0pswjnm7 2y agohttps://github.com/katef/libfsm/ https://github.com/katef/libfsm/