Section 11.37

Peak versus retained memory

Definition

Peak memory is the largest amount of memory in use at any single moment during a run or an operation. Retained memory is the amount still in use at a stated point after the operation ends, for example once an update has finished and its clean-up has run. “In use” means allocated and not yet released, in the memory categories the measurement covers. Peak memory decides whether the operation fits; retained memory decides what the operation leaves behind. A small retained amount says nothing about the peak.

The idea

A device replaces a 3 KiB table with a new 4 KiB version; one KiB (kibibyte) is 1024 bytes. The old table cannot be released until every reader still using it has finished, so for a while both tables exist. Memory in use is 3 KiB before the update, 3+4=73 + 4 = 7 KiB during the switch and 4 KiB afterwards. Measured afterwards, the update cost 4−3=14 - 3 = 1 KiB. But if 6 KiB is available for tables, every state fits except the switch, and the update fails.

Peak and retained memory answer different questions, like the peak occupancy of a car park and the number of cars left overnight. Two events of 300 cars each need 600 spaces if they overlap and 300 if they do not, and in both cases the car park can be empty at midnight. The picture stops at shape: any free space fits any car, but a memory request needs one unbroken free block, so scattered free memory can fail a request that the total free amount would allow.

Overlap comes from anything whose lifetime extends into another’s: an old and a new version kept together for a safe switch or for rollback, as in an A/B update §8.10; a staging buffer filled while the old data is in use; a release deferred until readers finish, as in read-copy update §9.20 (RCU), which waits for a grace period §9.21, or in reference counting §9.22; concurrent requests; and buffers that a peripheral fills by direct memory access §4.36 (DMA) while the processor works on other data.

How it works

  1. Fix the accounting boundary. Say which categories count, such as heap allocations, stacks, fixed pools, DMA buffers and statically allocated data, and whether the measure is the bytes requested or the allocator’s blocks, which add a header and alignment §4.22 padding to each request.

  2. Record every change. Log each allocation and release in order, or keep two numbers inside the allocator: the current total, updated at each allocation and release, and the high-water mark, the largest value the current total has reached. The total can rise only at an allocation, so the high-water mark equals the peak for the memory that allocator manages.

  3. Read the two values. The peak is the largest total over the run; the retained memory is the total at the stated point, after every deferred release due by then has run.

  4. Repeat the operation and record the retained memory after each repetition. Steady growth points to a memory leak §4.8 or to a growing cache; an unchanged value means the operation releases what it takes.

  5. Treat stacks separately. Stack painting finds a stack’s high-water mark: fill the stack area with a known byte pattern before the run, and afterwards find the deepest byte that no longer holds the pattern.

Reading the total at fixed intervals can miss a short peak. Also, an allocator usually keeps released memory for reuse instead of returning it to the operating system, so the memory the operating system reports for a process can stay high after the program has released everything. State which level a figure describes.

Worked example

A run has two phases. Phase A holds a 3 KiB buffer from 0 milliseconds until it releases the buffer at 10 milliseconds. Phase B holds a 4 KiB buffer until 20 milliseconds. Consider two schedules.

The memory retained after 20 milliseconds is 0 in both schedules, so the retained figure cannot tell them apart. Adding the two phase peaks, 3+4=73 + 4 = 7 KiB, gives the right answer for the overlapping schedule and overstates the sequential one by 7−4=37 - 4 = 3 KiB.

Sampling misses short peaks. A monitor that reads the total every 5 milliseconds, at 0, 5, 10, 15 and 20 milliseconds, sees 3, 3, 4, 4 and 0 KiB in the overlapping schedule. Its largest reading, 4 KiB, misses the 7 KiB that lasted only from 8 to 10 milliseconds. A high-water mark kept inside the allocator records 7 KiB at the moment B allocates.

Retained growth. An update is run three times, and the memory retained after each run is 0.5, 1.0 and 1.5 KiB. Each run leaves 0.5×1024=5120.5 \times 1024 = 512 bytes behind. If the growth continues, 1000 updates retain 1000×512=512,0001000 \times 512 = 512{,}000 bytes, which is 512,000/1024=500512{,}000 / 1024 = 500 KiB: a memory leak, unless the growth stops at a limit, as the growth of a bounded cache would.

Stated precisely

Let mi(t)m_i(t) be the number of bytes in use in category ii at time tt, for categories i=1,…,ki = 1, \dots, k (for example heap, stacks and pools) and for times tt in an observation window from 0 to TT. The total in use is M(t)=∑i=1kmi(t)M(t) = \sum_{i=1}^{k} m_i(t). The peak PP, and the retained memory R(τ)R(\tau) at a stated point τ\tau, are P=max0≤t≤TM(t),R(τ)=M(τ).P = \max_{0 \le t \le T} M(t), \qquad R(\tau) = M(\tau). MM changes only when memory is allocated or released, so the maximum is reached immediately after some allocation. Four facts follow.

  1. R(τ)≤PR(\tau) \le P for every τ\tau in the window. A small retained amount therefore gives no upper bound on the peak.

  2. maximaxtmi(t)≤P≤∑i=1kmaxtmi(t)\max_i \max_t m_i(t) \le P \le \sum_{i=1}^{k} \max_t m_i(t): the peak lies between the largest single-category peak and the sum of all category peaks. The right-hand inequality holds because at every moment each mi(t)m_i(t) is at most its own maximum. It is an equality only when all categories reach their maxima at a common moment.

  3. Readings at sampled times t1,…,tJt_1, \dots, t_J give maxlM(tl)≤P\max_{l} M(t_l) \le P: sampling gives a lower bound on the peak, never an upper bound.

  4. PP describes the run observed. Another input or another thread schedule can overlap the categories differently. A bound that holds for every run needs an argument about which allocations can be live at the same time.

Limits and common mistakes

A final zero, or any small retained amount, does not bound the peak.

Adding the peaks of separate categories or phases gives a safe upper bound only if every category is included and each peak is itself correct; it overstates the peak when the separate peaks happen at different times. Leaving out a category, such as a stack, a pool, a DMA buffer or memory awaiting a deferred release, understates the peak.

A peak that fits in the heap does not guarantee success. Allocator headers, alignment padding and heap fragmentation §4.9 can leave no single free block large enough for a request even when the total free space suffices.

Retained memory depends on the stated point. Measured before a deferred release has run, for example before the grace period of RCU ends, it includes memory already scheduled for release. State the point, or report both values.

Growth in retained memory across repetitions is a memory leak only if it does not stop; a cache that fills up to a fixed limit also grows at first.

Counting every allocation costs time (instrumentation overhead §11.32), which can change thread timing and therefore which allocations overlap.

Questions answered

Can two individually small phases overlap to produce a larger peak?

Yes. Peak memory, the largest total in use at one moment, counts everything that is live at that moment, so two phases whose lifetimes overlap add up even if each is small on its own. A phase that holds 3 KiB (kibibytes; 1 KiB is 1024 bytes) and a phase that holds 4 KiB need only 4 KiB at peak if the first releases its memory before the second allocates, but 3+4=73 + 4 = 7 KiB if the second allocates while the first still holds its memory. In both cases the memory retained after both phases can be 0, so a measurement taken at the end cannot tell the two cases apart.

Typical overlaps are an old and a new version kept together during an update or for rollback, a staging buffer filled while the old data is still in use, releases deferred until readers have finished, requests served concurrently, and buffers that hardware fills on its own. To find the true peak, record allocations and releases in order, or keep a high-water mark (the largest total reached) inside the allocator. Reading the total at intervals can miss a short overlap.

Related entries: Static versus dynamic footprint (§11.38), Instrumentation coverage (§14.35), Instrumentation overhead (§11.32), Memory leak (§4.8), Heap fragmentation (§4.9), Read-copy update (RCU) (§9.20).