MemReporter.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include "MemReporter.h"
  2. USING_NS_BF;
  3. MemReporter::MemReporter()
  4. {
  5. mCurEntry = &mRoot;
  6. mRoot.mName = "Root";
  7. mShowInKB = true;
  8. }
  9. MemReporter::~MemReporter()
  10. {
  11. }
  12. int MemReporter::GetChildSizes(Entry* entry)
  13. {
  14. int childSizes = 0;
  15. for (auto& childPair : entry->mChildren)
  16. {
  17. auto child = childPair.mValue;
  18. childSizes += child->mSize + GetChildSizes(child);
  19. }
  20. return childSizes;
  21. }
  22. void MemReporter::Report(int depth, Entry* entry)
  23. {
  24. String str;
  25. for (int i = 0; i < depth; i++)
  26. str += " ";
  27. str += entry->mName;
  28. while (str.length() < 64)
  29. str += ' ';
  30. if (entry->mChildSize == -1)
  31. entry->mChildSize = GetChildSizes(entry);
  32. if (mShowInKB)
  33. str += StrFormat("%6d %6dk %6dk\r\n", entry->mCount, entry->mSize / 1024, (entry->mSize + entry->mChildSize) / 1024);
  34. else
  35. str += StrFormat("%6d %6d %6d\r\n", entry->mCount, entry->mSize, (entry->mSize + entry->mChildSize));
  36. BfpOutput_DebugString(str.c_str());
  37. Array<Entry*> entries;
  38. for (auto& kv : entry->mChildren)
  39. {
  40. auto* entry = kv.mValue;
  41. entry->mChildSize = GetChildSizes(entry);
  42. entries.Add(kv.mValue);
  43. }
  44. entries.Sort([](Entry* lhs, Entry* rhs) { return (lhs->mSize + lhs->mChildSize) > (rhs->mSize + rhs->mChildSize); });
  45. for (auto& entry : entries)
  46. {
  47. Report(depth + 1, entry);
  48. }
  49. }
  50. void MemReporter::BeginSection(const StringView& name)
  51. {
  52. Entry** entryPtr;
  53. if (!mCurEntry->mChildren.TryAdd(StringImpl::MakeRef(name), NULL, &entryPtr))
  54. {
  55. mCurEntry = *entryPtr;
  56. mCurEntry->mCount++;
  57. return;
  58. }
  59. auto newEntry = mAlloc.Alloc<Entry>();
  60. newEntry->mCount++;
  61. newEntry->mName = name;
  62. newEntry->mParent = mCurEntry;
  63. *entryPtr = newEntry;
  64. mCurEntry = newEntry;
  65. }
  66. void MemReporter::Add(int size)
  67. {
  68. mCurEntry->mSize += size;
  69. }
  70. void MemReporter::Add(const StringView& name, int size)
  71. {
  72. BeginSection(name);
  73. Add(size);
  74. EndSection();
  75. }
  76. void MemReporter::EndSection()
  77. {
  78. mCurEntry = mCurEntry->mParent;
  79. }
  80. void MemReporter::Report()
  81. {
  82. Report(0, &mRoot);
  83. }