| 1 | // -*- C++ -*- |
| 2 | |
| 3 | /* |
| 4 | |
| 5 | Heap Layers: An Extensible Memory Allocation Infrastructure |
| 6 | |
| 7 | Copyright (C) 2000-2020 by Emery Berger |
| 8 | http://www.emeryberger.com |
| 9 | [email protected] |
| 10 | |
| 11 | Heap Layers is distributed under the terms of the Apache 2.0 license. |
| 12 | |
| 13 | You may obtain a copy of the License at |
| 14 | http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | |
| 16 | */ |
| 17 | |
| 18 | |
| 19 | #ifndef HL_PROFILEHEAP_H |
| 20 | #define HL_PROFILEHEAP_H |
| 21 | |
| 22 | #include <cstdio> |
| 23 | |
| 24 | // Maintain & print memory usage info. |
| 25 | // Requires a superheap with the size() method (e.g., SizeHeap). |
| 26 | |
| 27 | namespace HL { |
| 28 | |
| 29 | template <class SuperHeap, int HeapNumber> |
| 30 | class ProfileHeap : public SuperHeap { |
| 31 | public: |
| 32 | |
| 33 | ProfileHeap (void) |
| 34 | : memRequested (0), |
| 35 | maxMemRequested (0) |
| 36 | { |
| 37 | } |
| 38 | |
| 39 | ~ProfileHeap() |
| 40 | { |
| 41 | if (maxMemRequested > 0) { |
| 42 | stats(); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | inline void * malloc (size_t sz) { |
| 47 | void * ptr = SuperHeap::malloc (sz); |
| 48 | // Notice that we use the size reported by the allocator |
| 49 | // for the object rather than the requested size. |
| 50 | memRequested += SuperHeap::getSize(ptr); |
| 51 | if (memRequested > maxMemRequested) { |
| 52 | maxMemRequested = memRequested; |
| 53 | } |
| 54 | return ptr; |
| 55 | } |
| 56 | |
| 57 | inline void free (void * ptr) { |
| 58 | memRequested -= SuperHeap::getSize (ptr); |
| 59 | SuperHeap::free (ptr); |
| 60 | } |
| 61 | |
| 62 | private: |
| 63 | void stats (void) { |
| 64 | printf ("Heap: %d\n", HeapNumber); |
| 65 | printf ("Max memory requested = %d\n", maxMemRequested); |
| 66 | printf ("Memory still in use = %d\n", memRequested); |
| 67 | } |
| 68 | |
| 69 | unsigned long memRequested; |
| 70 | unsigned long maxMemRequested; |
| 71 | }; |
| 72 | |
| 73 | } |
| 74 | |
| 75 | #endif |