cmemory-managementembeddedfragmentation

How to calculate fragmentation?


Imagine you have some memory containing a bunch of bytes:

++++ ++-- ---+ +++-
-++- ++++ ++++ ----
---- ++++ +

Let us say + means allocated and - means free.

I'm searching for the formula of how to calculate the percentage of fragmentation.

Background

I'm implementing a tiny dynamic memory management for an embedded device with static memory. My goal is to have something I can use for storing small amounts of data. Mostly incoming packets over a wireless connection, at about 128 Bytes each.


Solution

  • As R. says, it depends exactly what you mean by "percentage of fragmentation" - but one simple formula you could use would be:

    (free - freemax)
    ----------------   x 100%    (or 100% for free=0)
        free
    

    where

    free     = total number of bytes free
    freemax  = size of largest free block
    

    That way, if all memory is in one big block, the fragmentation is 0%, and if memory is all carved up into hundreds of tiny blocks, it will be close to 100%.