r/programming • u/NX18 • Jun 03 '22
Benchmarking Malloc with Doom 3
https://www.forrestthewoods.com/blog/benchmarking-malloc-with-doom3/5
u/dinnertork Jun 04 '22 edited Jun 04 '22
The reason to avoid malloc is that slow paths can involve acquiring a lock, but the issue isn't the median (or even maximum) time that lock is expected to be held -- it's that merely holding a lock from another thread at all can trigger priority inversion given that the audio thread is already expected to be running with realtime priority.
Because higher (and especially realtime) priority threads can delay or prevent context-switching into lower priority threads (such as those on which malloc's mutex may be waiting), the realtime audio thread is essentially creating its own deadlock.
Now, you can certainly avoid this in your own mutexes by using pthread_mutex_trylock or PTHREAD_PRIO_INHERIT (which macOS grants automatically to all non-RW locks regardless), but the official malloc API provides no such control or guarantees.
1
u/xmsxms Jun 04 '22 edited Jun 04 '22
He seemed to completely ignore the fact the allocations are performed across threads with the locking overhead that implies.. that is why they can be slow. Just replaying them all from a single thread won't show you much at all.
Even if he recorded which thread the malloc occurred in and tried to replay using threads it still wouldn't give you much idea as it all comes down to timing and blocking/unblocking.
4
u/wintrmt3 Jun 04 '22
You did not read the whole article, did you? He measured allocations that are freed in a different thread (2.9%).
30
u/drobilla Jun 03 '22
The main reason
mallocand such things are considered cardinal sins in audio software isn't because they are "slow". It's because they're unpredictable, highly variable between platforms, and a potential context switch, which means losing your time slice with the scheduler. That is a "flaming death" scenario for serious real-time audio. It may not be for games, but that is why the engineering camps have different views on things likemalloc. The domains and their priorities are just different.You can't extrapolate how fast a simple
mallocbenchmark is to how well the approach works for reliably processing real-time audio while pushing the limits of the system (which these days, means concurrently on many threads, among other things). Just as games are always on the bleeding edge of real-world systems' rendering capabilities, pro audio software is always on the bleeding edge of real-world systems' computing capabilities.From an audio developer's point of view, things like this read how I imagine a "Why
known_sketchy_thing()Is Good Enough to Render 1 640x480 Rectangle at 15 FPS" article would to a graphics developer. Yes... and?