381 points · by gslin · 3y ago · 358 comments
> O(n^2) is the sweet spot of badly scaling algorithms: fast enough to make it into production, but slow enough to make things fall down once it gets there.
https://randomascii.wordpress.com/2021/02/16/arranging-invis...
How I cut GTA Online loading times by 70% https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times...
I'm playing a game (Fenyx Rising) and after launching it I always wonder why "Checking for additional content" screen takes 20-30 seconds. I'm pretty sure it should be just a single request.
The runtime for the release day store inventory count may have been okay, but I don't think that Rockstar kept profiling their game every time that they modified their store inventory.
The amount of pain Rockstar inflicted on their 90K+ users shows that Rockstar didn't care that their game took more than 3 mins to startup for the majority of their users.
But the profiling is all done on the game loop; I've never heard of any teams profiling the startup...
"everytime this blog is linked, I end up reading the whole thing"
I don't think it was accidentally quadratic. More likely, it was exponential.
For something mission critical like a bootloader that's more valuable than turning O(n^2) into O(n log n). People running systems like BSD largely don't care how long the system takes to boot, once it's booted the system runs for years.
Source: written sorts in assembly more times than I would care to count.
You can't always rely on smarter people to be there to do things for you. And you also can't rely on the standard library to have been written by smarter people anyway, and even if so, to have been written by smarter people in order to handle the situation you find yourself in. There's lots of ways to sort, and lots of good reasons to choose ways that are less than optimal for the use cases they end up being used in.
It seems to be any prolonged discussion about which sorting algorithm should be used is sort of skipping the elephant. Why is the list not sorted to begin with?
Without that basic knowledge it isn't very productive to focus on implementation details, no matter how fun the sorting exercise is. Deleted code is fast code.
One could argue that the database engine should be "smarter", but it's not. Note that data could be added or removed in the meantime, so the database engine can't really cache the result. See also https://stackoverflow.com/questions/70519518/is-there-any-be...
https://use-the-index-luke.com/sql/partial-results/fetch-nex...
Otherwise using offset usually is OK idea. Because users very rarely will inspect page #2153. They're interested with page 1, sometimes page 2. limit/offset works fine for those cases and it'll work for page 2153 for those who visit it once in a decade. Using ids makes logic to trac prev/next/page number incredibly complex and generally you don't need it.
For good performance this also requires that your search criteria (if any) be compatible with this index.
it doesn't seem mentioned in the HN thread the cause here is probably the same thing O(n^2): sorting. laying out icons is only linear if the icons are read in the order that they're placed. It's been a long time since I used windows regularly but my memory is the default placement is by creation time. So if they're read off disk by filename (or some sort of hash) they'd need to be sorted by timestamp.
Reasons? Firstly, you’d have to know the entries are sorted. For that, you need an API that tells you that or hard-code information about file systems in your code. They may exist, but I’m not aware of any file system API that provides that information.
Secondly, the file system may not return the names sorted in the locale you want to sort them in.
Thirdly, the sorting code used in the file system may contain a bug. Once file systems are out there, you can’t fix them (happened in one of Apple’s file systems. HFS, IIRC)
Lastly, modern GUIs tend to sort file names containing numbers non-alphabetically, so that, for example “file 2.jpg” gets sorted before “file 12.jpg”.
So, I think it’s easier to always sort. I would pick an algorithm that works well when items are mostly sorted at the start, though.
(More realistically, below people are discussing that in the kernel environment the set of standard or third party library available may be unavoidably limited)
(I think this was the check) https://github.com/freebsd/freebsd-src/blob/main/lib/libc/st...
I mean, clearly it wasn't good enough otherwise they would have used it, no? Perhaps integrating it was a huge faff.
This makes no sense to me. What about C makes it hard to use a good library?
A lot of languages now have common tooling (cargo for rust, pip for python, etc) which makes it easier to find and incorporate the libraries you want. Apparently there are tools like https://conan.io/ but they're not as widely-adopted.
C's build system is similarly non-uniform. Many packages use Makefiles, others use different build mechanisms.
C has no universally-agreed error handling mechanism or convention. Whether exceptions or golang's error interface, you can generally assume that a random package in most languages will handle errors the way you expect. In C it's a lot more varied.
Similarly memory allocation - sometimes in a larger application you want to customize how malloc and friends work. How and whether you can do that for a C package is non-uniform.
Mind you the C standard library has a sort() function which will have sensible big-O behavior on pretty much any platform. I suspect this specific problem is more to do with this being kernel-mode code which has a lot of special conditions.
Now do it in C/C++. Absolute nightmare.
Look at how many header-only C++ libraries there are out there. They're making compilation time drastically worse purely to avoid the need to faff with a shitty build system. It's a good trade-off too. I use header-only libraries where possible. They're convenient and popular.
Actually vcpkg seems to be going some way to fixing that but I have yet to convince my co-workers to use it.
Though this has not much relevance here as it is about assembly.
It's easy to lose sight of the climb once you're at the top.
It doesn't have templates/generics.
having said that this specific sort is somewhere deep in kernel boot land. and kernel code can't really use the standard library. I am not sure if there is a standard kernel sort.
https://twitter.com/cperciva/status/1659391725427720195?t=0y...
Note that I want to stress that that is no reason for some folks to stop focusing on it. And kudos on the improvement. Criticism, if any, here is that statistics once again rears its head to make something feel bigger by using a percent.
If whoever is fixing this depend on quickly launching instances in Firecracker, it's their problem. And that's how open source is usually done
So, realistically, assuming that Colin is a decently paid software engineer, I find it doubtable the savings from this particular change will ever add up to mean anything even close to what it costs to have just one person assigned to it.
Now, every other change they found up to this point may help sway that needle, but at this point, though 7% is a lot of percent, they are well into the area where savings they are finding are very unlikely to ever be worth finding.
Edit: I saw that qsort does indeed get it into basically zero at this range of discussion. I'd love to see more of the concrete numbers.
1. He was already profiling the system, which is almost certainly where the bulk of his eng costs are
2. This is one piece of a larger optimization story, he has made many many changes to significantly improve performance
3. This is a trivial change
4. 500 Firecracker executions is nothing - FaaS targets 10s of thousands of executions per second
Given (1) and (3) in particular the only sensible thing Colin could do other than fix this is ignore it, which seems insane.
I had servers that took up to 5 minutes from start/reboot to GRUB prompt. And they were not some 60 drive monsters but typical dual CPU 1U servers...
Half of the devices were just powered by USB and not using any data, but only needed to be ON when the PC is ON.
The way it worked:
- FreeBSD would scan all USB devices
- get held up on some for no reason
- find a hub
- scan everything on a hub
- find another hub
- scan everything on that hub as well
Anytime during the scan it could run into a device that takes longer (no clue which or why, only happened on FreeBSD and never on Linux or Windows)
I'm sure windows and linux did the same thing, but both shapely continued booting while FreeBSD waited and waited and waited and waited.
Bias light on a monitor would sometimes completely stop the process until unplugged.
USB stack on FreeBSD is forever cursed, I still remember kernel panics when you unplug a keyboard or a mouse.
It's not impossible that it's some archaic and since long invalid legacy thing along the lines of "let's wait 5 seconds here just in case the drive hasn't managed to spin up, despite the computer having been powered on for 15 seconds already, because that happened once in 2003 on someone's 1989 HPPA system so we need to support that case". I'm not joking, this is really what I imagine it being about.
There were (or still are?) SCSI drives that would not spin up until told to over the bus. I think the idea is to not do them all at once since the motor draws a lot of power.
I'm fairly sure I've run into drives that would not respond on the bus while spinning up.
And if it happens with SCSI drives, it may happen with other types.
At least looking in my dmesg on linux all SATA drives are getting ready rougly at same time 0.6 s into boot AHCI driver gets initialized and 3.2 seconds into boot they are all up. Looks parallel too as ordering does not match log order
[ 3.192274] sd 6:0:0:0: [sdc] 500118192 512-byte logical blocks: (256 GB/238 GiB)
[ 3.192277] sd 7:0:0:0: [sdb] 3907029168 512-byte logical blocks: (2.00 TB/1.82 TiB)
[ 3.192277] sd 8:0:0:0: [sda] 5860533168 512-byte logical blocks: (3.00 TB/2.73 TiB)also why cant freaking boot process be optimized after first boot? bsd is essentialy sorting SAME thing every boot, THAT is ridiculous. sort once, save order ( list, sysinit000000000000 ), boot fast next time. hardware or other change or failed boot, can trigger start sorting bull for safety.
you know what youre booting into, so sort it once then run it from saved order next time. how many times you change hardware on computer ? and if you do, you can just restart with grub flag, toggle switch in control panel before restart, etc
And you really want to do this automatically, with no manual anything, because (among other reasons) if you need to swap a part on a broken machine, you do not want that to needlessly break the software. So you're sorting regardless, and so you might as well just be unconditional about it.
you can define shutdown flag for hardware change: shutdown -rF XD,
some things are hot swappable and for that there has to be logic (in kernel) to know you have new hardware...
if you have total hardware failure that can be detected too, on next boot...
...vs just putting quicksort in
I suspect much of the delay comes from the nature of plug-and-play. The OS has to poll every bus and every port to find every device, then query those devices to determine what they are, then load a driver and actually configure them. It simply can't rely on the hardware being exactly the same from one boot to the next.
Ah yes, let's brick the OS when hardware fails and has to be replaced without advance notice.
im saying you can have two pathways, ( decision which route to choose is almost zero cost )
first - when you boot correctly, you can save information that you booted correctly.
second - if you do not find information about safe boot, you go old route, quicksort route.
( YES. you can do that, in a way you do not have loops of boot process because you are reading boot is ok even if it is not. just dont be lazy like linux kernel developers were, when i was telling them this exact thing few years back. )
I'd consider this less "haha dum code is slow" and more "you are booting the kernel way too much, even a 1.97 millisecond delay is noticable".
Shaving ms off the boot of that VM is a performance boost of that lambda (or whatever the cloud vendor calls it).
Er, didn't NetBSD accomplish that... like a decade ago, now? Or is FreeBSD looking into supporting rump kernels?
Of course, calling anything that takes place in less than a blink of an eye "slow" is overstating things... lol :-)
If only I could get my desktop environment to come up in less than 28ms :-)
BUT
that we use solutions across multiple problems instead providing solution specifically for that problem. if you have KNOWN vm, on KNOWN hardware then why you need all kinds of hardware and other bull.. initializations, checks.... ? just provide list of things it has to have then after list is run over without problem, continue. also why would amazon/gcp/azure care ? they are making money from you running inefficient solutions....
It would be great if that changed though...
My tv boots a kernel, Alexa's, laptops, cars etc.
And this might be not specifically critical but it's a sign of people just doing something less optimal
If someone did not optimize this this might indicate other optimizations
Why do we even need to waste any consciousness-seconds on watching electric circuits initialize? Computers should just start working
I assume it's not just once when I first turn on my laptop from fully off. Is it once every time I restart a Docker container? (Assuming FreeBSD images.)
Is it something that runs a couple times a day, a dozen times a day, a thousand times a day? Fifty times every time I open an Electron app?
I suspect this doesn't matter and is more a curiosity, but I wouldn't be shocked to learn otherwise.
That is, until someone searches for e.g. git conflict markers.
At a glance looks like 13.1-RELEASE booted 3x faster than 11.1-RELEASE, and 14.0-CURRENT on Firecracker boots 45x faster than 11.1-RELEASE on a c5.xlarge
I showed them how long it took to run the O(n^2) on 100000 elements, about two minutes on my beefy server. Then I showed them the O(n) version running on my comparatively weaker laptop, and it took about ten seconds to run a million elements. The students were genuinely kind of impressed, and I stressed the point to say that "these are the kind of numbers that make it important to take theory seriously."
At the end of the day, boot times are determined not by technical reasons but by how much the users are willing to tolerate. If the market demanded low boot times, the engineers would deliver.
But seriously, there is a router that I shall not name here that spends 10 seconds sleeping to avoid a race condition after initializing some irrelevant service. And of course the entire boot process depends on this service.
Realizing this one clause is what helped me understand so much, including economics and traffic (induced demand). I call it the "misery constant."
Number of lanes doesn't matter: People will adjust their lifestyles until they arrive at the highest level of misery they can tolerate. Add a lane and wait for equilibrium to reestablish at exactly the same level of congestion as before.
Add a 10,000% (more??) increase in CPU and disk speed from the 128K Macintosh to the MacBook Pro, and oh look, it takes basically the same amount of time to boot or to launch an application as it did then, as the developers adjusted their wastefulness until they achieved the maximum level of delay the customers were willing to bear.
You wouldn't even be able to initialize CPU & DRAM in "couple of milliseconds"
Loading BIOS from flash alone would eat that budget few times over
Reliability is an issue here. There's all sorts of bits and pieces where it's miserably difficult to get a signal or event that something has come up, or there is such a mechanism and it's unreliable. Especially when there's third-party closed drivers or firmware involved. So somebody ends up giving up and putting the delay in, testing it a few hundred times, and declaring it done.
But yes, lots of systems could come up faster if enough people cared.
Perhaps this is part of what Windows does -- I know that it basically keeps a hibernated image of the non-logged-in RAM state, for use when you shut down (and it throws it out if you do an explicit Restart, for troubleshooting reasons)
Worth noting that Fedora, RHEL/CentOS/et al, Debian, Ubuntu, Arch and derivatives use systemd, so odds are pretty high if you use "Linux" you also get systemd
Outside of toy projects, interviews, and teaching them, I've never actually written a sort function. I never saw the point; the sort function built into the standard library of whatever language I'm using is probably faster and/or more space efficient than whatever thing I whip up in a few seconds.
Of course, that's a privileged opinion that I am afforded by the fact that my entire career has been "Java and higher" languages.
Relatedly:
Q: When is Python faster than C?
A: When the C programmer used a linked list or some O(n^2) algorithm because they didn't have a standard library full of easy to use well implemented data structures and algorithms.
Like, yes, no question, if you try and implement a tightloop in Haskell vs C, C is going to come out a lot faster.
However, no one writes Haskell like that! People rely pretty heavily on standard libraries (or even third party libraries), and on the optimizations afforded to them by the "rich" language of Haskell.
C might be capable of being faster, but that doesn't imply that a C program will inherently be faster than a similar Haskell program, especially if the programs are relatively large.
It's not just getting your hands dirty, you need to be strategic about where you want to spend your time.
I don't think so, regarding the linked list. In almost every case you'll end up with at least as much pointer indirection in Python. But yeah, if you have enough data that complexity starts mattering a worse algorithm will cause more problems.
... downthread ...
> I suspect quicksort will be enough though.
Somebody hasn't taken a freshman complexity theory class in a while...
(Note, this is tongue in cheek. Worst case is not average case and all that. I'm sure quicksort will do fine)
Also, the worst case would be "systems take 2 ms extra time to boot" so it's not exactly a disaster.
And perhaps even more unlikely if you permute the input sequence before sorting it.
I'm basing this off of my understanding of Skiena's discussion of quicksort in The Algorithm Design Manual.
My trick was stupid simple. The usual file I/O buffer size was 512 bytes, I made it 16K.
BSD is sometimes used in some iot-like devices, of which there are 3 billion. If I randomly assume 0.5% of those are running a fork of FreeBSD, that's 15 million devices. I'm also going to randomly assume that devices reboot once a month on average.
That all comes out to 4.2 days/year saved! Wow!
https://www.wolframalpha.com/input/?i=2ms+*+3+billion+*+0.5%...
CONNECTION *c = malloc(num_nodes * num_nodes * sizeof(CONNECT_STRUCT));
And almost the entire matrix was empty because most things in a network aren't connected to each other. I spent a a few minutes replacing that with a hash table on the (i, j) node pair.“FreeBSD/Firecracker now boots to a login prompt in 782 ms. 170 ms of this is spent generating a self-signed TLS certificate for sendmail, because of course it is.”
On the gripping hand, it's mad that it's still Sendmail, although that is going to change. It's 2023, and the fact that a FreeBSD system still has the traditional ~2000 lines of indistinguishable-from-line-noise "DO NOT EDIT THIS" stuff in /etc/mail/sendmail.cf, complete with whole bunches of rules for UUCP, is rather amazing.
I wonder how many small FreeBSD systems out there are spending their time double-bouncing cron-job mail that cannot be delivered. (-:
I suspect Firecracker is set up to be as quick to initialize as possible, but still that a vanilla (ie not an optimized fork) can do that ... My phone takes a two orders of magnitude more!
I hope your BSDCan talk is getting recorded.
Both C++ and Rust have pretty nice sorting algorithms in the standard library. C does not (qsort doesn’t really count as a nice sorting algorithm which is why so many C programmers took their own).
I could imagine that qsort is not an option in FreeBSD for example because it is recursive and there is no stack at that level, or there is a risk of stack overflow. If that's the case, shell sort should be fine I guess.
https://doc.rust-lang.org/core/primitive.slice.html#method.s...
(It's interesting that the stable `sort`, by contrast, is only available in `std` because it uses an allocating timsort-variant.)
C is technically also split, so called "freestanding" C implementations don't provide features like stdio but they do have e.g. math functions. C++ attempts something similar but it's a bit hit-and-miss as a truly "free standing" C++ doesn't entirely make sense, as systems that try to use C++ for very low level work often discover.
The next less relevant observation is that Rust chooses to call these sort and sort_unstable - the one that's guaranteed to be available doesn't get the easier name, that's reserved for the one that definitely doesn't have unexpected behaviour. If you don't know what an "unstable" sort is, then sort_unstable's behaviour might in some cases be astonishing. Some languages make the opposite choice, which means programmers may use sort, not realising it's actually an unstable sort because the entire concept was never explained to them.
This is one of many examples of Rust's safety achieved not via some sophisticated technology but just by thinking about why people screw up. Every Rust programmer who without thinking writes sort gets a stable sort, if that was too slow, they can choose sort_unstable, but doing so prompts them to consider, wait, is an unstable sort correct here?
Finally the least relevant but hopefully still interesting observation is that it is quite possible to have a stable sort which doesn't require allocation, but the performance is not so hot. It seems pretty unlikely that you must have a stable sort and you can't afford an allocator and yet you don't mind the performance hit. As I understand it though some C++ libraries do offer this.
[0]: https://twitter.com/bsdphk/status/1659568675899228163
[1]: https://github.com/freebsd/freebsd-src/commit/d89a1b600fc071...
So that's why the sort-SYSINIT objects code didn't use qsort.
I'd also guess that there were fewer SYSINIT objects to sort back in 1995 than today.
see ~line 150 of sys/kern/init_main.c in https://github.com/freebsd/freebsd-src/commit/2b14f991e64ebe...
IIRC qsort will use a merge-sort on glibc when it can do so without growing the heap.
If I'm understanding correctly, we're talking about sorting integers. Would something like radix sort not be more appropriate? Or is there a reason to still prefer a more generic sorting algorithm?
https://twitter.com/cperciva/status/1659577625289928705
So this bubble sort is just under 2ms.
I think it's cool to find and optimize that, he says he'll put in a qsort and that's great. But 2ms? Probably not a huge deal.
We did managed to throw away few thousand lines of code of fixed init scripts after moving to systemd and get rid of few other stuff so it has been positive but definitely some of the bad with a lot of good. Journald logging format is also kinda fucked that causes some nasty edge cases
Except of systemd-resolved, this utterly radioactive piece of shit can go fuck itself.
https://github.com/systemd/systemd/issues/2460
Long story short: there is no useful indexing in journald DB format which means looking for say "last message app emitted" means looking thru every file.
As long as it is mmaped in or on tmpfs it is reasonably fast, but if you say have last 1GB of logs stored on spinning rust on NAS.... you either have 3-4 second wait till it finds those few log lines, or buffer cache littered with that GB of logs, pushing out actually useful stuff.
It literally have worse performance than grepping entire /var/log last time I checked.
And it seems in its entirety it was "Lennart wanted to make a binary log format" vs something actually useful... just having SQLite DB instead would on top of being faster far more useful (ability to SQL query logs on local node with no extra fuss would be awesome)
-somebody who accepted a bet
"The kernel boot (of which 7% is bubblesort) is 28 ms."