| 1 | // -*- C++ -*- |
| 2 | |
| 3 | #ifndef HL_STATS_H |
| 4 | #define HL_STATS_H |
| 5 | |
| 6 | #include <map> |
| 7 | #include <cassert> |
| 8 | |
| 9 | namespace HL { |
| 10 | |
| 11 | template <class SuperHeap> |
| 12 | class InUseHeap : public SuperHeap { |
| 13 | private: |
| 14 | typedef std::map<void *, int> mapType; |
| 15 | public: |
| 16 | InUseHeap() |
| 17 | : inUse (0), |
| 18 | maxInUse (0) |
| 19 | {} |
| 20 | void * malloc (size_t sz) { |
| 21 | void * ptr = SuperHeap::malloc (sz); |
| 22 | if (ptr != NULL) { |
| 23 | inUse += sz; |
| 24 | if (maxInUse < inUse) { |
| 25 | maxInUse = inUse; |
| 26 | } |
| 27 | allocatedObjects.insert (std::pair<void *, int>(ptr, sz)); |
| 28 | } |
| 29 | return ptr; |
| 30 | } |
| 31 | |
| 32 | void free (void * ptr) { |
| 33 | mapType::iterator i; |
| 34 | i = allocatedObjects.find (ptr); |
| 35 | if (i == allocatedObjects.end()) { |
| 36 | // oops -- called free on object i didn't allocate. |
| 37 | assert (0); |
| 38 | } |
| 39 | inUse -= (*i).second; |
| 40 | allocatedObjects.erase (i); |
| 41 | SuperHeap::free (ptr); |
| 42 | } |
| 43 | |
| 44 | int getInUse () const { |
| 45 | return inUse; |
| 46 | } |
| 47 | |
| 48 | int getMaxInUse () const { |
| 49 | return maxInUse; |
| 50 | } |
| 51 | |
| 52 | private: |
| 53 | int inUse; |
| 54 | int maxInUse; |
| 55 | mapType allocatedObjects; |
| 56 | }; |
| 57 | |
| 58 | |
| 59 | template <class SuperHeap> |
| 60 | class AllocatedHeap : public SuperHeap { |
| 61 | public: |
| 62 | AllocatedHeap () |
| 63 | : allocated (0), |
| 64 | maxAllocated (0) |
| 65 | {} |
| 66 | void * malloc (size_t sz) { |
| 67 | void * ptr = SuperHeap::malloc (sz); |
| 68 | if (ptr != NULL) { |
| 69 | allocated += SuperHeap::getSize(ptr); |
| 70 | if (maxAllocated < allocated) { |
| 71 | maxAllocated = allocated; |
| 72 | } |
| 73 | } |
| 74 | return ptr; |
| 75 | } |
| 76 | |
| 77 | void free (void * ptr) { |
| 78 | allocated -= SuperHeap::getSize(ptr); |
| 79 | SuperHeap::free (ptr); |
| 80 | } |
| 81 | |
| 82 | int getAllocated () const { |
| 83 | return allocated; |
| 84 | } |
| 85 | int getMaxAllocated () const { |
| 86 | return maxAllocated; |
| 87 | } |
| 88 | |
| 89 | private: |
| 90 | int allocated; |
| 91 | int maxAllocated; |
| 92 | }; |
| 93 | |
| 94 | |
| 95 | template <class SuperHeap> |
| 96 | class StatsHeap : public SuperHeap { |
| 97 | public: |
| 98 | ~StatsHeap () { |
| 99 | printf ("In use = %d, allocated = %d\n", SuperHeap::getInUse(), SuperHeap::getAllocated()); |
| 100 | printf ("Max in use = %d, max allocated = %d\n", SuperHeap::getMaxInUse(), SuperHeap::getMaxAllocated()); |
| 101 | } |
| 102 | }; |
| 103 | |
| 104 | } |
| 105 | |
| 106 | #endif |