Skip to content

Commit 97b1313

Browse files
committed
py/gc: Improve calculation of new heap size in split-heap-auto mode.
There are two main changes here to improve the calculation of the size of the next heap area when automatically expanding the heap: - Compute the existing total size by counting the total number of GC blocks, and then using that to compute the corresponding number of bytes. - Round the bytes value up to the nearest multiple of BYTES_PER_BLOCK. This makes the calculation slightly simpler and more accurate, and makes sure that, in the case of growing from one area to two areas, the number of bytes allocated from the system for the second area is the same as the first. For example on esp32 with an initial area size of 65536 bytes, the subsequent allocation is also 65536 bytes. Previously it was a number that was not even a multiple of 2. Signed-off-by: Damien George <damien@micropython.org>
1 parent 3270d85 commit 97b1313

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

py/gc.c

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -282,14 +282,28 @@ STATIC bool gc_try_add_heap(size_t failed_alloc) {
282282
// - If the new heap won't fit in the available free space, add the largest
283283
// new heap that will fit (this may lead to failed system heap allocations
284284
// elsewhere, but some allocation will likely fail in this circumstance!)
285-
size_t total_heap = 0;
285+
286+
// Compute total number of blocks in the current heap.
287+
size_t total_blocks = 0;
286288
for (mp_state_mem_area_t *area = &MP_STATE_MEM(area);
287289
area != NULL;
288290
area = NEXT_AREA(area)) {
289-
total_heap += area->gc_pool_end - area->gc_alloc_table_start;
290-
total_heap += ALLOC_TABLE_GAP_BYTE + sizeof(mp_state_mem_area_t);
291+
total_blocks += area->gc_alloc_table_byte_len * BLOCKS_PER_ATB;
291292
}
292293

294+
// Compute bytes needed to build a heap with total_blocks blocks.
295+
size_t total_heap =
296+
total_blocks / BLOCKS_PER_ATB
297+
#if MICROPY_ENABLE_FINALISER
298+
+ total_blocks / BLOCKS_PER_FTB
299+
#endif
300+
+ total_blocks * BYTES_PER_BLOCK
301+
+ ALLOC_TABLE_GAP_BYTE
302+
+ sizeof(mp_state_mem_area_t);
303+
304+
// Round up size to the nearest multiple of BYTES_PER_BLOCK.
305+
total_heap = (total_heap + BYTES_PER_BLOCK - 1) & (~(BYTES_PER_BLOCK - 1));
306+
293307
DEBUG_printf("total_heap " UINT_FMT " bytes\n", total_heap);
294308

295309
size_t to_alloc = MIN(avail, MAX(total_heap, needed));

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy