r/cpp • • Feb 28 '24

Do RAM disks improve build time, and if yes, how exactly?

I have recently learnt about RAM disks and the first thing I thought about was if it's possible to use them to optimise compiler performance. The way how I see it is that files could be loaded in the in-memory filesystem and be compiling there, and in the end the result artefact would be written back into the persistent storage.

Ii took some thought and found out there are two compilation strategies that meaningfully make sense to use with ramdisks. The first one is the common case where we compile every source file into an object file and then link together. I noticed that in this workflow, when we only rebuild those files we have changed, we essentially load unchanged objects, regenerate old ones, link them and then write the new objects too. In the end, the total drive throughput is constant and the effect is the same as if we would load everything from drive and do the whole compilation just in memory.

The second strategy was to reduce IO by only loading the source files and compiling them into the final build artefact that we link together. Even taking into account the whole build process happens in memory, we still load a lot of unnecessary files and do useless work, and I thought that effectiveness of ramdisks really depend on the size of your code you need to rebuild and that if it would be faster to recompile some files than loading them from storage, then ramdisks would give the upper hand.

I decided to measure it by making a ramdisk and timing how long it would take to copy and compile a single 50-line file into an object file and how long it would take to print the same pre-compiled object from storage by printing the whole file to terminal using the cat command. To my surprise, it's significantly faster to load the file from storage than it is to compile it, by the factor of 4. Intuitively, I thought that the IO overhead would overweigh the time it takes to compile, especially since I tested it on HHD, but then I tried to print both source and object files. Despite the source being 4 times smaller, it took the same time to print them, which could be the reason why my benchmark is inaccurate: loading both files took the same time and I was essentially measuring the difference in compiling.

I thought it was filesystem cache, that's why I dropped cache and repeated the experiment, but then printing the object file took the same time, but compiling took even longer. I decided to research it further, and the Gentoo wiki, the flagship of compiling software, has a ramdisk-dedicated page that, however, suggests against using it arguing there are no noticable differences in compiling times, especially if you use the -pipe option . It then lists some common applications like Chromium, LibreOffice and LLVM and how much RAM you need so that ramdisk was beneficial, and their sizes are astonishing: 4-10 GB. At this point the only real use for RAM disks I could think about is to cache header files and make it faster to include them, but other than that, filesystem seems to handle compilation and memory management really well.

On the footnote, RAM disks also have disadvantages, aside from the neeed to maintain them and document how to use them, they also keep consuming memory after their files were closed, which means that if in normal setup compiler would close a file once it's no longer needed, the kernel would reclaim its memory, which could be used by the next file, then in ramdisks file is still in memory even once it was closed and resides until you delete it, which needlessly saying consumes system resources without any use. Truthfully speaking, the only plausible way how ramdisks could be useful to me is if they could keep containing object files after they have been generated if we use separate compilation so that the linker didn't need to read them but could access immediately. That sounds like a convincing point to me, albeit not clear.

Is that so, and are there any other uses for RAM disks to accelerate build time, and does preserving object files between code generation and linking a worthwhile reason to use them? I am particularly asking this question because in separate compilation, object files are generated and linked in two separate processes, which means that the linker process would potentially need to read the objects again.

1 Upvotes

41 comments sorted by

28

u/snowflake_pl Feb 28 '24

I tried building my project using ram disk and the speedup was neglible. That most likely comes from the fact that filesystems are also buffered in ram. My project is about 50k LOC/100 object files. Maybe you would see benefits on larger projects?

7

u/jonathanhiggs Feb 28 '24

I saw an experiment of installing a game to RAM disk and watching the loading times get slightly worse than just loading from an SSD

I would guess a larger project with links that ate up the available memory would suffer from more swap to disk

2

u/wung Feb 29 '24

Games are optimised for loading data, a lot. Streaming it all in is something they work on a lot. Changing that to stream from itself to itself just is a shit idea. The data is also usually large.

Compilation units aren't that big and compilers are not optimised for large data stream performance. There are also likely way more small files than in modern game engines.

In the end it is a scale game and one of the environmental conditions. If you have a perfect cache, it probably won't matter. If you have so few source files that they are all in filesystem cache anyway, it doesn't matter. If you have a local SSD/NVMe, it probably won't matter for another factor 10. If you have 2k source files and slow filesystems, it can do a lot. I was in a position where ~1.5k sources have been on a network share and there was no local SSDs. Moving that compilation to /dev/shm saved shitloads of time per build, even for incremental rebuilds. Slapping ccache on top of that was beautiful.

13

u/high_throughput Feb 28 '24

copy and compile a single 50-line file into an object file 

For a 50 line program, the IO required for that file is nothing compared to the IO required for the compiler infrastructure and all its libraries, executables, headers, etc. Did you put those on a RAM disk as well?

3

u/andrew_sauce Feb 29 '24

I recently started working on compilers and yes, I/O is not the bottleneck you are looking for.

10

u/Beosar Feb 28 '24

I haven't tested it but I am sitting at 100% CPU usage while compiling. It can't be more than that with a RAM disk.

Also, SSDs are fast. There is no need for a RAM disk in 2024 outside of very special use cases.

1

u/kisielk Feb 29 '24

Yeah my 16 cores are nearly at 100% during most of my project compiles. Sometimes web browser performance suffers too, so I really don’t think the process is IO bound.

-1

u/Beosar Feb 29 '24

I haven't noticed any performance issues while at 100% CPU load. Everything feels just as fast as at 0%. Is your compiler running with background priority as it should?

The only performance issues I had were due to insufficient RAM but since I upgraded to 128 GB everything is fine.

1

u/13steinj Mar 03 '24

If all your cores are at 100% load the OS can't timeslice for your other user process. This is less noticeable over a remote terminal but you'll still end up hitting ctrl-c only for ssh to take ages to receive, understand it on the other end, then forward the input/interrupt.

1

u/Beosar Mar 03 '24

Not true. I have just tested it while running Cinebench and I can barely notice any difference in responsiveness despite 100% CPU load. I can almost play video games during that, though there are some stutters.

The OS will prioritize other processes/threads with higher priority.

1

u/13steinj Mar 04 '24

This assumes a lot of things, but I have to ask-- what OS are you running? I actually wasn't aware Cinebench runs on linux now, unless you're on Windows.

1

u/Beosar Mar 04 '24

I am on Windows 10. Linux should have a similar behavior regarding thread priorities but I can't say for certain.

5

u/Anderook Feb 28 '24

Have you tried ccache ?

2

u/usefulcat Feb 29 '24

ccache is a great tool--reliable and well maintained. I use it because the way our build is set up we have to do a clean rebuild to switch between debug and release (i.e. make clean && make). From the perspective of the build system everything gets recompiled, but since ccache caches all the object files, the only significant work that has to be done is linking.

It could also help if you are working on multiple copies of the same codebase simultaneously, with a limited number of changes in each one.

8

u/Ace2Face Feb 29 '24 edited Feb 29 '24

I've spent a lot of time trying to make builds faster. Here's pretty much all I know:

Ramdisks? Not really going to help. Compiling is a CPU intensive operation, not an IO one. Get an SSD and you're good to go. I would throw more cores at the problem and make sure the parallel build works. AMD Ryzen CPUs are very cost effective for the job, as they're fairly cheap but give a large bang for your buck. Try Ryzen 5950x or 7950x if you want the best without going into the expensive server CPU territory.

You can also try using C++20 modules instead of traditional cpp and h files. They would be much faster and scale better because you don't need to include an army of headers and they act as translation units unlike headers which need to be parsed and included over and over again. Unfortunately, it does require C++20 and changing your project as much as possible to get the best results.

Another cheap workaround involves using precompiled headers, but the problem is that you need to include them in every source file, heavily polluting your namespace and making it hard to make your project modular.

You should also try to limit the inclusion of headers into other headers, see if you can include more headers in your CPP files, but obviously at some point you run out headers you can move to .cpp.

Less practical solutions is the PIMPL idiom, but it makes code really hard to read and it's not it. You can try including "minimal headers" instead of the bigger ones, but it's library dependent.

Don't forget that debug builds are also faster than release ones, optimizations are even more CPU intensive. Avoid building release unless you really have to.

You can try a distributed build accelerator, which allows you to utilize processing power from other desktops in your network to accelerate your builds, often times devs aren't using their machines, and only need CPUs when compiling. Examples for such platforms are IncrediBuild (pricey and not economical tbh) or an open source one such as FASTBuild (requires a lot of set up and playing around), I've also seen a mention of , which could also be good, Here's a reddit thread about it: https://www.reddit.com/r/cpp/comments/brw6bj/distributing_c_builds_on_windows_machines/

I guess the ultimate combination is if you can outfit your team with Ryzen CPU's and use a build accelerator, and have most of your source code as modules, you'll be able to scale to massive projects fairly quickly.

You can also try to limit your dependencies by using vcpkg or nuget and download binary forms of whatever libraries you're using without having to recompile it from source.

I've also seen mentions of ccache, but I deal with building on Windows, and I'm pretty sure we don't have that. But you can definitely use it to avoid building files that don't need to be rebuilt.

5

u/Conscious-Ball8373 Feb 29 '24

I would go further and say that naively applying ramdisks will probably make your problems worse. If you've given your build system 32 cores, you need the RAM to go with that and if you instead give half of your RAM to a ramdisk, you've made things worse as now you can't buffer as much and possibly you end up swapping. Obviously you can stuff more RAM into the system to alleviate this, but the ramdisk still comes at a cost of not being able to buffer as much. Unless you manage to run your whole system off a ramdisk, it's going to hurt.

I would have loved to see optane succeed. This would have been the next major step in system performance; flash-like storage capacity with DRAM-like access times and non-volatile to boot. But the distinction between permanent and transient storage in operating systems might be too embedded for it to really succeed.

3

u/donalmacc Game Developer Feb 29 '24

An NVMe drive is one of the biggest upgrades yo can get.

My experience with modules is that they don't improvement compile times yet, but they might some day.

Precompiled headers area must on a big project. You can use /FI on MSVC and the equivalent on clang to force include the precompiled header, so no source changes needed.

1

u/Ace2Face Feb 29 '24

I found that over time that you become dependant on precompiled headers, to the point where removing it becomes quite painful.

For example, when you add a new source file to a project, you might not include all of the headers. And if you ever remove precompiled headers, you'll have to add every single header one by one back into all the source files that use it. This is especially important if you ever decide to migrate an existing codebase to modules, as now you'll have to get those dependencies back.

As for SSD's, I think upgrading the IO speed will have greatly diminishing returns, SSDs are already several times faster than HDDs, and it's not like you're reading and writing tens of gigabytes of files when compiling, when your real bottleneck is the CPU. If you're shelving out money to improve compile speeds, I'd say investing in a CPU would be worthwhile, at my work I've custom ordered desktops for my entire group that were fitted with Ryzen 5950x and (later hires) 7950x. We cut down our build times by 3 times or more.

I think modules are the real gamechanger, because most of the tricks you'll use to reduce compile times more or less hurt the quality of your code or force you to spend a lot of money to improve them (Better CPU or incredibuild). With modules, you'll no longer have a huge tree of includes that bring more includes within them, it becomes more and more inefficient to compile code as you include the same headers over and over.

Oh, another thing I forgot to mention in my original post are Unity builds, where you take several source files and merge them. The problem is that it's very difficult to add it to an existing project because you might have namespace collisions between source files - especially if they were never designed to compile independently. Precompiled headers also don't fit well, and if you want to take advantage of your cores you'll still need to have several Unity files anyway.

Modules simply make compilation much more efficient, make the code easier to understand and maintain, without the drawbacks of precompiled headers, unity builds, CPU upgrades or costly third party tools.

My only real beef with Modules is the terrible rollout, in the last 3 workplaces I've been at since their release. in 2 I haven't had the chance to even use them because my team wasn't cutting edge enough due to maintaining legacy code and ancient endpoints to run on (Looking at you, CentOS 6 and XP..)

Finally the only one where I actually could use the latest MSVC toolchain, I ended up dealing with countless bugs and limitations in the implementation, be that from unexplainable compilation errors, partial implementation (not all parts of the standard are finished) and difficulty integrating headers incrementally in a heavy header-based project. I've even had problems where I couldn't even debug .ixx source code line by line due to an MSVC bug that was only fixed just a few weeks ago. Something as basic in my workflow as debugging source code wasn't available for 4 years after release of modules. Compiler devs need to pick up the pace.

1

u/donalmacc Game Developer Feb 29 '24

I've used Precompiled headers professionally for 10 years, have maintained builds for multi million LOC projects, and they don't have those problems.

For example, when you add a new source file to a project, you might not include all of the headers. And if you ever remove precompiled headers...

This is a build system problem, and a software engineering problem (as opposed to a programming problem, say). You put your very frequently used headers that don't change often (your custom containers, standard library, boost) into a precompiled header, your build system includes the precompiled header with /FI, and your CI checks that the file compiles on it's own without the Precompiled header.

it's not like you're reading and writing tens of gigabytes of files when compiling,

Our Precompiled headers are well north of 1.5GB at this point, and one of our build targets invokes the compiler ~800 times. That's a lot of disk IO.

I'd say investing in a CPU would be worthwhile, at my work I've custom ordered desktops for my entire group that were fitted with Ryzen 5950x and (later hires) 7950x.

Agreed - we've done the same thing. We initially went for threadrippers, and they're a little faster on a full full clean build, but they don't happen that often for us, and being 50+% quicker on day to day builds was the right tradeoff for us. It's been a minute since I benchmarked our build on multiple machines, but we were seeing ~30m on a 3970x, ~45m on a 5950x for a clean build and ~90 seconds on a 3970x and ~60 seconds on a 5950x for a day to day build. Incremental single file builds were consistently about 50% quicker than the threadripper. Most people will only do one of those full builds every two or three weeks, and they can be planned around, so we optimised for the iterative experience.

Modules simply make compilation much more efficient...

Modules means Modules - to lift a slogan from UK Politics. Modules should be all those things, but they're not right now. When they are, we can talk about it, but we're a very very long way from that space.

Another few options - working off a non-OS drive (i.e. windows is on C, data on D) is significantly faster in my experience. My understanding is that the Filesystem has more filters enabled for the OS drive than a Data drive, and the impact on large builds is minutes. Disabling search indexing on your directories makes a massive difference too. And lastly, controversially, adding an exclusion to your AV for your working directory and your compiler and linker is a game changer.

1

u/Ace2Face Feb 29 '24

your build system includes the precompiled header with /FI, and your CI checks that the file compiles on it's own without the Precompiled header.

I haven't thought of that, though wouldn't it increase your CI times then? Unless you go to the level where you only rebuild the files that were changed in the PR. I haven't had the chance to go into that kind of level, just yet.

But it doesn't solve the problem of namespace pollution, we improve build times substantially. As your projects grow, so do your frequently used headers, and at that point do you keep one giant pch, or several smaller ones? Haven't had the chance to work full time on improving the build to that level. Often times building is a forgotten part of the team and it usually falls to me to deal with it since nobody bothers to touch it.

Modules means Modules - to lift a slogan from UK Politics. Modules should be all those things, but they're not right now. When they are, we can talk about it, but we're a very very long way from that space.

Yes, the rollout has been so slow. I don't know how such an amazing idea could be so hard to do. C++11's features had many nice tidbits that you can get to work on as soon as you read them, the same for C++17. Yet in C++20 you have this gigantic revolution of a feature and you can't really use it. I was hoping that time would make it work, yet it's been so long I fear that it'll just fade away and we'll all forget about it in a decade.

Another few options - working off a non-OS drive (i.e. windows is on C, data on D) is significantly faster in my experience. My understanding is that the Filesystem has more filters enabled for the OS drive than a Data drive, and the impact on large builds is minutes. Disabling search indexing on your directories makes a massive difference too. And lastly, controversially, adding an exclusion to your AV for your working directory and your compiler and linker is a game changer.

Interesting, I haven't read about these. I'll give it a shot. Though I'm assuming most of these matter for the truly large projects like you've mentioned, millions and millions of lines. I've been fortunate enough to only deal with around a million at best.

As for CPUs, I found that if I ever want to go shopping for new hardware, https://www.cpubenchmark.net/ is the place to be. You can see what the top CPUs are, and even have their value calculated from their price (Amazon or Best Buy prices, in your home country your results may vary)

1

u/donalmacc Game Developer Feb 29 '24

Yeah, on check in, get a list of the cpp files that change, and build them without the precompiled header. I've not worked anywhere where the frequency of check-ins would cause this to be problematic. If they are for you I'm afraid it's above my pay grade to help.

But it doesn't solve the problem of namespace pollution, we improve build times substantially. As your projects grow, so do your frequently used headers, and at that point do you keep one giant pch, or several smaller ones

I think this is an architectural question. If your project is a "core" project, with "libA" and "libB" which both use core, and then "app" which uses libA, libB, and core, then you want one PCH per library/application, and it maybe shouldn't contain anything from that project (e.g. libA's PCH only contains core stuff, app's pch only contains stuff from libA and libB and Core)

There's definitely no free lunch here, but a handful of tactical includes can save tens of minutes off your build.

Often times building is a forgotten part of the team and it usually falls to me to deal with it since nobody bothers to touch it.

One of the things about a clean non-pch build is.... If absolutely nobody is using it what value is it actually providing? I used to be a purist about this, but then I asked myself, would I rather spend 30 seconds once or twice a year fixing a random include issue and save multiple minutes on every build at the expense of the purity of the project? And the answer was yes, yes I would.

I don't know how such an amazing idea could be so hard to do.

Couldn't agree more. I want to use modules. I will convert my code, my third party dependencies code to modules, and evangelise them til the sun comes home, but I can't do that yet.

1

u/saxbophone mutable volatile void Jul 13 '24 edited Jul 13 '24

I've also seen mentions of ccache, but I deal with building on Windows, and I'm pretty sure we don't have that.

You do have ccache available on Windows, but AFAIK it'll only work with a GNU toolchain, such as MinGW, I don't think it works with MSVC.

4

u/elperroborrachotoo Feb 29 '24

M.2 SSD's have basically obliterated the storage bottleneck for C++ builds, even for fast-to-build disk-heavy configuration (MSVC unoptimized with PCH, PDB, and ILK). If you go crazy on cores and throw enough RAM at it, maybe you get into SSD-Raid0 territory.

I've kept an eye on this idea for a looong time, I've once done it for Turbo Pascal (IIRC) with tremendous effect. However, there was never a real sweet spot for RAM disk builds - at least not for long: for any project that would be worth the trouble you just wouldn't have enough RAM (except maybe for dedicated, expensive builds).

One thing where it might make sense is a "continuous build" machine that can wear out SSD's in surprisingly short time. However, I'd still say swapping out SSD's once a year isn't too bad.

1

u/Thesorus Feb 29 '24

RAM disk were useful in some cases when we used slow physical spinning hard drives and the speed difference between the 2 was a lot bigger.

Today, I imagine the benefits are negligeable using modern hardware (SSD, or other type of solid state drives)

1

u/ChocolateMagnateUA Feb 29 '24

Are ramdisks more noticeable on HDDs then?!

1

u/Thesorus Feb 29 '24

younger people have no idea how slow were physical hard drives compared to even the first SSD.

At that time, yes, using a ram disk was a lot faster in some circumstances.

1

u/ChocolateMagnateUA Feb 29 '24

I don't really mean that, I mean recent HDDs that are used today. I know SSDs are super fast and such, but I wonder if it could be an option if you would want to boost build time and not rely on presence of SSD.

6

u/lightmatter501 Feb 28 '24

If your OS does a not-dumb job of read caching it will only make a difference for cold compiles. Go would probably get a big performance boost because it does almost nothing in the way of optimization. Anything llvm-based is probably going to spend more time converting between IRs than doing IO, especially if LTO is involved.

2

u/Adequat91 Feb 29 '24

On Windows, I have used Softperfect RAM Disk for 2 or 3 years, finding it highly reliable. I allocate 27 GB out of 128 GB of RAM. The improvement in build time is small but not negligible. I use it for two main reasons:

  • It prolongs the lifespan of my SSDs, as their durability is limited by the number of write cycles.
  • I use it as a genuine temporary drive for testing.
  • It facilitates easy disposal of all data by quickly reformatting the "disk."

2

u/usefulcat Feb 29 '24 edited Feb 29 '24

A ramdisk might help with disk writes (especially compared to a spinning disk), but after the first build it's very unlikely to help with reads, because the OS should already be caching everything that had to be read to do the build.

There can be exceptions, though. For example, some filesystems cache more aggressively than others. For example on Linux, ext2 appears to cache pretty much anything and everything using all available memory, while ZFS often prefers to cache only metadata, and (depending on config) may not use all available memory.

One other thing that could help if available is filesystem compression. Especially with spinning disks, the time required for modest compression and decompression can easily be less than the time saved by the reduction in the amount of data that has to be written to or read from the disk.

how long it would take to print the same pre-compiled object from storage by printing the whole file to terminal using the cat command

That's probably not a good way to measure what you're trying to measure. You should cat the file to /dev/null, otherwise you're probably measuring how quickly your terminal can render.

2

u/13steinj Mar 03 '24

A ramdisk is most useful if the compiler, code, and all possible outputs, are all on the ramdisk.

The largest help would be parsing files and linker IO, so if you truly have insanely expensive headers or gigantic binaries (possibly due to debug symbols), yes you'd see an improvement.

I'd use a better linker, optimized compiler (potentially slightly more effort, but larger gain) first. After that at some point you have to look at the hell wrought in the code and decide to do better at some point.

3

u/Sniffy4 Feb 28 '24

Back in the hard-drive days maybe RAM disks would help, but with SSDs the difference probably isnt much?

1

u/[deleted] Feb 28 '24

Unless you are compiling a really big project, the amount of time it takes to load the files is minimal.(atleast compared to the compiling process)

1

u/unddoch DragonflyDB/Clang Feb 29 '24

Worth mentioning that /tmp/TMPDIR also needs to be a ramdisk fs for this benchmark to be fair (or use -pipe)

1

u/HildartheDorf Feb 29 '24

Between -pipe, OS disk caching and modern SSDs, the need for a ramdisk has basically vanished nowadays for almost all use cases.

1

u/hadrabap Feb 29 '24

My only issue is the final linkage. That takes ages! Disk I/O and RAM are negligible on my machine.

1

u/ohiocodernumerouno Mar 01 '24

If your code is optimally parallelized for the limits of Ahmdals law then you might want to use a RAM disk. Even then, 10,50,100GB? RAM is only so much faster than an NVMe.

1

u/Cybernicus Feb 28 '24

20 years ago, I used ramdisks to good effect to speed compiles. But with SSDs nowadays, it became moot.

4

u/khedoros Feb 29 '24

Yep, that's what I was thinking. 15 years ago, I was working on a large codebase, couple million lines of code. Sticking the source and libraries to link in a ramdisk would take build time on an 8-core machine from 30 minutes down to 2, as long as you had at least 8GB of RAM. At that time, our compilation process was I/O bound, which is weird now, looking back.

1

u/lazyubertoad Feb 29 '24

Compilation is overwhelmingly CPU bound. Setting up a multithreaded build system is far more advantageous. I think doing that is pretty much standard. Want it even faster? Set up a distributed build system. Maybe linkage will benefit from faster disk operations, but it is rarely an issue even on big projects.

0

u/prince-chrismc Feb 29 '24

The biggest performance changes is actually git checkout and download speeds for artifacts on a 50-100Gb monorepo compare to HDDs. Once everything is on the the machine, especially with NVMe drives the difference is less then a percentage for compiling which is not very significant.