Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 846
Bigbohne Avatar asked Jan 03 '11 18:01

Bigbohne


2 Answers

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%.

like image 59
psmears Avatar answered Oct 21 '22 22:10

psmears


Calculate how many 128 bytes packets you could fit in the current memory layout. Let be that number n.

Calculate how many 128 bytes packets you could fit in a memory layout with the same number of bytes allocated than the current one, but with no holes (that is, move all the + to the left for example). Let be that number N.

Your "fragmentation ratio" would be alpha = n/N

like image 26
Nicolas Viennot Avatar answered Oct 22 '22 00:10

Nicolas Viennot