How do I make make/ninja limit parallelism based on memory pressure? : <p>If I use <code>make -j2</code>, it builds fine, but under-utilizes CPU:</p>

<p><a href="https://i.stack.imgur.com/gYhxt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gYhxt.png" alt="j2"></a></p>

<p>If I use <code>make -j4</code>, it builds fast, but for some particular template-heavy files it consumes a lot of memory, slowing down entire system and build process as well due to swapping out to HDD:</p>

<p><a href="https://i.stack.imgur.com/qKxol.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qKxol.png" alt="j4"></a></p>

<p>How do I make it automatically limit number of parallel tasks based on memory, like this:</p>

<p><a href="https://i.stack.imgur.com/KN4jW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KN4jW.png" alt="enter image description here"></a></p>

<p>, so that it builds the project at maximum rate, but slows down in some places to avoid hitting memory wall?</p>

<p>Ideas:</p>

<ul>
<li>Use <code>-l</code> and artificially adjust load average if memory is busy (load average grows naturally when system is already in trouble).</li>
<li>Makes memory allocation syscalls (like  sbrk(2) or mmap(2)) or page faults keep process hanged until memory gets reclaimed by finished jobs instead of swapping out other processes. Deadlock-prone unfortunately...</li>
</ul>
