872 points · by ruleabidinguser · 9y ago · 334 comments
The long-standing advice when writing GNU utilities used to be that if the program you were replacing was optimized for minimizing CPU use, write yours to minimize memory use, or vice-versa. Or in this case, if the program was optimized for simplicity, optimize for throughput.
It would have been very easy for the nascent GNU project to unintentionally produce a line-by-line equivalent of BSD yes.c, which would have potentially landed them in the 80/90s equivalent of the Google v.s. Oracle case.
https://www.gnu.org/prep/standards/standards.html#Reading-No...
https://github.com/coreutils/coreutils/blob/ccbd1d7dc5189f46...
https://github.com/coreutils/coreutils/commit/35217221c211f3...
This is the beautiful part of Unix: small tools that do only one thing well. Programs following this philosophy are very good abstractions. They do one very well defined thing so you can use them without having to understand how they work. I have used Unix for years and I've never felt the need to read the source code for `yes`. And because they do a very small thing, even if you need to read them, the overhead of optimization is not that much, for example, the optimized GNU yes is just under 100 LOC if you remove comments and help boilerplate. Yes, it's longer than the BSD version, but it's just a matter of minutes to understands what it does.
I'm glad it runs fast, and I hope that all OS utilities are optimised (and tested, of course!) instead of making their source code pretty. The fact is, most people want to use programs, not read them.
I actually checked just now, and it looks like you'd be making twice as many system calls with /dev/zero compared to generating the data locally:
strace dd count=1 bs=512 if=/dev/zero of=test
open("/dev/zero", O_RDONLY) = 3
dup2(3, 0) = 0
close(3) = 0
lseek(0, 0, SEEK_CUR) = 0
open("test2", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
dup2(3, 1) = 1
close(3) = 0
read(0,"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 512) = 512
write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 512) = 512
close(0) = 0
close(1)
While 'strace yes > test2' is just a constant stream of write() calls.The difference matters if you're benchmarking e.g. some new SSD compared to a tmpfs on a machine with 100+ GB of RAM. It's always better if the tools have less overhead, because the comparison is more meaningful.
Also consider that it can be faster to write to a local network than to disk. I've never done it, but I imagine that the kernel's not going to want to deal with your /dev/zero calls if it's spending all of its time writing to a 10GB switch. I can imagine some very specialized storage servers that could spend most of their time writing from memory buffers to a network switch, or if you're troubleshooting a slowdown in the networking itself.
yes(){ while :; do echo "${1:-y}"; done; }
Python: import sys
while True:
if len(sys.argv) > 1:
print(sys.argv[1])
else:
print("y")
And if you don't need the features of `yes` and only need a loop that prints 'y', then there really is hard to beat the simplicity of: while:; do echo "y"; doneJust because you say so?
When I saw this item here I reached for the terminal and wrote a simple (and non-compliant) alternative that simply initialises 8150 bytes of "y\n" and then loops a write forever. I understand that it is not a fully standard-compliant yes, and that maybe GNU yes is indeed fast, but that awfully simple program that takes all of 10 lines (everything included) and took me all of a minute to write performs just as well as far as pv is concerned.
(I eventually completed a feature complete yes but I still think that simply not using `puts` is hardly optimising to the limit.)
https://github.com/lattera/glibc/blob/master/string/strlen.c
https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/x86...
The pcmpeqb instruction is from SSE 4, it compares 16 bytes per op
Naturally it could be that the C function puts used by most people in OpenBSD is implemented with built in EINTR catching loop, or that OpenBSD do not interrupts writes.
As you say, the GNU versions definitely handle EINTR - the linux man page for puts() just says it returns a non-negative value on success, it's not even specified whether it returns the number of bytes written or not.
But the point stands; there's no error handling in the OpenBSD version. But that could be considered a design decision; the OpenBSD version never gives up on writing data until you kill it; the GNU version bails at the first error.
I think unix v6 was mostly as clear. Linux suffered the real world penalty. But maybe BSD managed to keep it's source poetic.
atexit (close_stdout);
Aren't all streams closed at exit? And why closing stdout, anyway?
Why would it be slower to do a single, say, 8190 bytes write instead of 2730 3-byte writes?
It's just a trade off. For utilities whose behaviour doesn't change we're happy to improve the speed.
Someone does a Go version and gets the same speed as GNU yes. Someone else tries several languages. This person got the same speed in luajit, and faster in m4 and php. Ruby and perl about 10% slower, python2 about 10% slower still, and python3 about half that. The code is given for all of these, and subsequent comments improved python3 about 50% from his results, but still not up to python2.
[1] https://www.reddit.com/r/programming/comments/6gxf02/how_is_...
what is going on with the m4 code?
(use std::borrow::Cow;) ?!
(I don't know rust, its on my list.. Especially with cow borrowing! They clearly are my people).
I noticed they added a comparison of Rust to gnu yes on the thread. They only got: 2.17GiB/s but on a slower machine.. (2.04 for the GNU)
[1]: https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpris...
(haven't run the tests myself though)
edit: haven't noticed the comment by dom0.
[1] https://www.reddit.com/r/programming/comments/6gxf02/comment...
darwin with BSD + GNU yes, vs some scripting langs:
$ /usr/bin/yes | pv > /dev/null
^C00MiB 0:00:04 [23.9MiB/s] [ <=>
$ /opt/local/libexec/gnubin/yes | pv > /dev/null
^C77GiB 0:00:05 [ 644MiB/s] [ <=>
$ bash -c 'while true; do echo "y"; done' | pv > /dev/null
^C38KiB 0:00:03 [ 233KiB/s] [
$ node -e 'while (true) { console.log("y"); }' | pv > /dev/null
^C57MiB 0:00:03 [ 582KiB/s] [
$ perl6 -e 'loop { print "y\n" x (1024*8) }' | pv > /dev/null
^C295MiB 0:00:02 [ 139MiB/s] [ <=>
$ ruby -e 'while true do puts("y"*1024*8) end' | pv > /dev/null
^C14GiB 0:00:09 [ 827MiB/s] [
$ python2.7 -c 'while True: print "y\n" * (1024*8),' | pv > /dev/null
^C.3GiB 0:00:10 [1.73GiB/s] [ <=>
$ python3.6 -c 'while True: print("y\n" * (1024*8)),' | pv > /dev/null
^C73GiB 0:00:05 [1.79GiB/s] [ <=>
$ perl -C0 -E 'print "y\n" x (1024*8) while 1' | pv > /dev/null
^C.6GiB 0:00:08 [1.84GiB/s] [ <=> > $ python2.7 yes.py | pv > /dev/null
> ... [7.22GiB/s] ...
> $ python3.4 yes.py | pv >/dev/null
> ... [8.76GiB/s] ..If you write the Python script using bytes (not Unicode), then Python 3 is faster than Python 2, at least for me. Python 3 is 20 % slower than GNU yes and Python 2 35 % slower than GNU yes.
e: I think in your last sentence you are comparing results from different computers.
yes | rm -r large_directory
yes | fsck /dev/foo yes | rm -r <>
and not rm -rf <> yes "" | cat -n
to generate a sequence number.OK, may be I misunderstood, who ran yes, the customer or the genius?
> In 2006, the yes command received publicity for being a means to test whether or not a user's MacBook is affected by the Intermittent Shutdown Syndrome. By running the yes command twice via Terminal under Mac OS X, users were able to max out their computer's CPU, and thus see if the failure was heat related.
I always assumed it was busywork to make the customer feel better.
I don't understand this reasoning. Why is it being limited to main memory speed? Surely the yes program, the fragments of the OS being used, and the program reading the data, all fit within the L2 cache?
For each byte of data passing through pv:
1. the byte is read from yes memory to CPU registers by the write syscall handler in the kernel
2. the byte is written to kernel's internal buffer associated with the pipe
3. the byte is read back in the read syscall called by pv
4. the byte is written to a buffer in pv memory
5. and thas's the end because write syscall executed by pv on /dev/null very likely doesn't actually bother reading the submitted buffer at all
edit: Actually it might only be 20GB/s because on Linux pv seems to use the splice syscall to transfer data from stdin to stdout without copying to userspace.
This is also the reason why further "optimization" of this program in assembly was a fool's errand: the bulk of CPU load is in the kernel.
The actual throughput then, once you include OS copying, is either 2 or 4 times the quoted speed (depending on splice usage), so we're either at main memory theoretical speeds, or double main memory speeds. Intuitively, I'd still have expected that it should be a larger multiple.
(A quick search can't find me any reliable Intel L1/L2 cache speeds/multiples to quote, so I admit this comment is more speculation than it should be!)
See eg. https://stackoverflow.com/questions/23599074/system-calls-ov... who benchmarked it at ~638ns per "read" call.
(Many, many years ago I was working on the Zeus web server, and we went to surprising lengths to avoid syscalls for performance.)
https://www.reddit.com/r/unix/comments/6gxduc/how_is_gnu_yes...
There's no reason that the L2 cache needed to be flushed at any point - the caches are all dealing with physical memory, rather than virtualised address space, so the fact that there are two processes here shouldn't stop the caching from working.
And pv on the other side of the pipe should use splice().
Now that would be a complete zero-copy I/O path, purely limited by the CPU, not by memory bandwidth. It would benchmark at hundreds of GB/s :)
https://www.reddit.com/r/unix/comments/6gxduc/how_is_gnu_yes...
Good catch, I just noticed that it does.
https://github.com/freebsd/freebsd/commit/1d61762ca37c20ab6f...
It's about twice as fast as GNU yes now on my FreeBSD system here.
Update: They fixed that issue with this follow up https://github.com/freebsd/freebsd/commit/2592fbb8
# /usr/local/bin/yes | pv > /dev/null
11.5MiB 0:00:09 [1.02MiB/s] [ <=>]
# /usr/bin/yes | pv > /dev/null
1.07GiB 0:00:09 [ 142MiB/s] [ <=>]
JavaScript wins again!!The top comment is:
"It's a shame they didn't finish their kernel, but at least they got yes working at 10GiB/s."
which as an OS guy, someone who has been working on Unix for 30+ years, as a guy who was friends with one the QNX kernel guys (they had perhaps the only widely used microkernel that actually delivered), that's hugely amusing and spot on. The GNU guys never really stepped up to being kernel people. Bitch at me all you want, they didn't get there. It's a funny comment, especially coming from reddit.
We must not be reading the same Hacker News...
Anyway, the comment you're quoting is just a shallow jab that belittles the GNU developers' work without contributing anything new or meaningful. It's telling that you had to spend two paragraphs to justify cross-posting it here.
Jokes have their place, but bringing up the failure of Hurd in every GNU-related post is banal. And saying they "never really stepped up" to your level as a mighty kernel developer, as if the people who brought us glibc and coreutils lack an understanding of OS internals, just seems rude and curiously out of touch.
However, as avip found out below, it does still render OS X useless within less than a minute (at least on my 2015 MBP).
bash: xrealloc: cannot allocate 18446744071562067968 bytesBut before that, parent shell has to buffer until EOF. With "yes" output being unbound, this means unbound buffering / memory growth. That is, until OOM killer take notice and shut it down.
Whole thing will probably take few seconds to a minute (depending on how much free RAM there is vs. how fast it is), peg a single CPU core in the process, and will recover cleanly (except for shell in question being terminated).
...unless system in question has single CPU and large+slow swap. Then yes, bring-it-to-its-knees.
RAM can be tweaked by preventing Linux heuristic overcommit via sysctl vm.overcommit_memory=2. (0 is only recommended if you do not run broken applications. It so happens that many JS and Java VMs are broken on memory pressure.)
Not complaining, I like this kind of analysis
But it seems you won't be limited, in a shell script, by the speed you can push y's
Somebody wanted to optimize 'yes', so they did. There doesn't need to be a good reason, just like there doesn't need to be a good reason for a person to read a certain book or watch a certain movie, other than they want to do it.
And it does make sense for Open Source code because the resources are limited hence other features and/or bug fixes might be more important than pushing data at full speed
That's not how open source works, though. There's not a group of people obligated to work on the GNU utilities. There's not a central project manager ordering people around telling them what changes to make.
Declaring that 'yes' is generally fast enough already doesn't imply that it was fast enough for the person who spent their time optimizing it. Somebody needed (or just wanted) 'yes' to be really fast, so they did the work and submitted the changes back.
This is software engineering. Thinking about the tradeoffs and whether they are appropriate or warranted is bread and butter. It very much makes sense to ask whether all of this is merely optimizing for a benchmark at the expense of other factors that might turn out to be more important, such as long term maintainability, portability, behaviour in some common cases which are significantly unlike the benchmark, and so forth.
Several people have made some of these points here and in other discussions; and not only do they make sense, they are an important part of the discipline.
Is the optimized implementation documented well enough that other people coming to it anew can understand it in another 10 years' time? How many of the magic constants have to be tweaked as the operating system evolves? Is it clear to maintenance programmers how they need to be tweaked? Does optimizing for the benchmark skew the implementation too far away from one common case where one is only wanting a few "y"s (because, say, the program being told "y" only asks 17 questions) resulting in every invocation of the yes program rapidly generating KiBs or even MiBs of output, that lives in pipe buffers in kernel space unused and only to be thrown away? Does it make more sense to put buffer size optimizations in the C library where all can benefit? What is the benefit of optimizing for Linux-only system calls on GNU Hurd? Will we optimize yes for GNU Hurd, too, in the same codebase? How much conditional compilation will we end up with? If the C library is improved to do better in the future, is it a problem that the optimized for benchmark program no longer automatically gains from it? How much of a problem is it that a GNU program is now not portable to systems other than Linux, and is locked into one operating system?
And what about other benchmarks? Many have noted that this benchmark pretty much relies on the fact that the output of the yes program is simply thrown away, and no real work is being done by anything else on the system. What about a benchmark where it is? What about a benchmark where it is important that yes issues a system call per line, yielding the CPU to other processes so that they can process that line before yes bothers to print the next? What about a benchmark that measures kernel memory usage and treats lower as better? What about benchmarks that measure how small the yes program is; not just in terms of code but in terms of memory, I/O, and CPU usages; because the memory, I/O, and CPU should actually be given to more important programs than yes on the system that are actually the system's main function? What about low impact?
Yes, it's fun to focus narrowly and optimize yes so that it generates as much output as it can for one specific toy usage. But in engineering one has to ask and think about so much more.
As a result you can process very large volumes of data and consume (not waste, consume) significant system resources to perform your processing.
Make the static array BUFSIZ * 1024 to trim the syscalls by a factor of 1000.
This is amazing. Maybe we can turn this into a verb? "I Volkswagened the common cases with precalced buffers".
So, what's the distribution of #bytes read for runs of 'yes'? If we know that, is GNU 'yes' really faster than the simpler BSD versions?
Also, assuming this exercise still is somewhat worhtwhile, could startup time be decreased by creating a static buffer with a few thousand copies of "y\n"? What effect does that have on the size of the binary? I suspect it wouldn't get up much given that you can lose dynamic linking information (that may mean having to make a direct syscall, too).
Wouldn't that be entirely negligible compared to starting the program in the first place?
Why did the GNU developers go to such lengths to optimize the yes program? It's a tiny, simple shell utility that is mostly used for allowing developers to lazily "y" there way through confirm prompts thrown out by other shell scripts.
is this a case of optimization "horniness" (for lack of a better word) taken to its most absurd extreme, or is there some use case where making the yes program very fast is actually important?
Source: https://github.com/coreutils/coreutils/commit/35217221c211f3...
I've personally used it for generating repeating text and filling disks in system testing, so I appreciate it being faster at those tasks. I also sometimes use it as a signal generator for a hacky load generator, like so:
yes | xargs -L 1 -P NUM_PROCESSES -I {} curl SOME_TARGET_URL > /dev/null
This doesn't benefit from being faster per se, but I appreciate it using less CPU since I want to give curl as much system resources as possible.I would write() the buffer each time it gets enlarged, in order to improve startup speed.
Also: The reddit program has a bug if the size of the buffer is not a multiple of the input text size.
And it's increasing the buffer by incrementing one at a time, instead of copying the buffer to itself, reducing the number of loops needed (at cost of slightly more complicated math).
If "only few yes's are needed" then the slowdown to produce them will be inconsequential, whether they still fill a buffer in this case or not.
yes | ssh server "cat > /dev/null"
But yes take arguments so there might be more use cases: $ man yes
NAME
yes - output a string repeatedly until killed
SYNOPSIS
yes [STRING]...
yes OPTION
DESCRIPTION
Repeatedly output a line with all specified STRING(s), or 'y'.One could put a write in the memcpy loop, so that first it writes one copy of the string, then two, then 4, 8 (etc.), meaning time to first byte is short, but it quickly gets up to the eventual asymptotic speed with a full buffer.
( https://www.reddit.com/r/rust/comments/4wde08/optimising_yes... )
The author appears to be aware of that:
> Even with the function overheads and additional bounds checks of GNU's yes
How about a /proc/bin/yes for this? Like most /proc files, it would appear to be empty. Executing it would involve a fs/binfmt_proc.c file in the kernel source, which would be a handler for this sort of executable. That would get the job done entirely in the kernel.
`yes` will help me on the "see what happens when something uses all the CPU and memory" test case. Thanks Reddit/HN!
I also had to do the same test on windows, so python won
After reading here so many unfair critics and pedantic dislike over PHP[1][2][3][4][5][6], I just want to say: STFU.
[1] https://news.ycombinator.com/item?id=12706136
[2] https://news.ycombinator.com/item?id=3825227
[3] https://news.ycombinator.com/item?id=3824881
[4] https://news.ycombinator.com/item?id=1823022
[5] https://news.ycombinator.com/item?id=1819517
[6] https://news.ycombinator.com/item?id=1819413
... Just to name a few.
[quote]
It's hard to find a worse example than php, because when many "bad" languages fail in one or the other category, php seems to fail in most categories.
* Java has a really repetitive syntax, but it's libraries might make up for that.
* C++ with all it's features has bazillion ways to shoot yourself, but it's arguably fast and the syntax is bearable. ...
[/quote]
FWIW, when I run the tests there's no substantial difference between Perl, LUA, or PHP.
I am not sure what was the last time I had to choose a language by a single dimension. If we are talking about performance, scripting languages rarely shine. On the top of that, performance critical things in scripting languages are often implemented in a compiled language (like Pandas for example).
Except that, in the yes example, PHP shines by its performance.
Of course, you don't choose a language based on that on a single dimension, but speed is an important factor otherwise benchmarks would not exist.
>OS X just uses an old NetBSD version similar to OpenBSD's >NetBSD's is 139MiB/s, FreeBSD, OpenBSD, DragonFlyBSD have very similar code as NetBSD and are probably identical,
It really depends on how fast your memory and processor are. Everything there was benchmarked with an i7-4790 with DDR3-1600, and very very little running in the background.
Can we have a new flag for posts by people who don't know what they're doing so I can skip them? I am serious.