How do I predict serious memory fragmentation issue is likely to happen?
Can I check the page fault time or 开发者_Go百科something else.. :)
No question is stupid. If you're worried about memory fragmentation you will need to rework how you allocate memory so you can track it. Perhaps you should overload the new
operator in those classes where you feel fragmentation would cause the most harm. Use some sort of logging functionality to write to you where it all is going. That should suffice as a first exercise. Then if you find that it really is harming you, you can create chunks of memory of the right size to guarantee your items are aligned in the manner you wish them to be.
Are you on windows? There is a Low-fragmentation Heap available there that can be used as a preventative measure. It only takes a few lines to set up and should help with these issues.
You use HeapSetInformation to set it. Something like this should do the trick:
ULONG hi = 2;
HeapSetInformation(
(HANDLE)_get_heap_handle(),
HeapCompatibilityInformation,
&hi, sizeof(hi));
If you are using C++, I wouldn't bother trying to predict it. The nice thing that encapsulation gives you is that you can at a later date change the memory allocation strategy without breaking all existing code. So I would do nothing and see if fragmentation does actually occur in real-life circumstances - it very probably won't.
AFAIK memory fragmentation is likely to happen when there is a lot of allocation and deallocation of small objects.
Have a look at Boost.Pool to prevent memory fragmentation.
http://www.boost.org/doc/libs/1_41_0/libs/pool/doc/index.html
An indication of fragmentation would be for example, if your system reports having 5MB free but you are unable to allocate large chunks (like 1MB) at a time. This suggests that your system has some free memory but it has been chopped up into small non-contiguous pieces.
Your mem fragmentation is largely due to the data structures you use and your memory manager. You can usually assume any lib you want to use will have lots of memory fragmentation. To completely stop it you need to use data structures that minimize these issues and try to avoid allocating and deallocating data uneccessarily and possibly tackle memory manager itself.
精彩评论