profiler.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "profiler.h"
  2. #include "stackcollect.h"
  3. #include <util/generic/algorithm.h>
  4. #include <util/generic/singleton.h>
  5. #include <util/generic/string.h>
  6. #include <util/generic/vector.h>
  7. #include <util/stream/str.h>
  8. namespace NAllocProfiler {
  9. namespace {
  10. static TAllocationStackCollector& AllocationStackCollector()
  11. {
  12. return *Singleton<TAllocationStackCollector>();
  13. }
  14. int AllocationCallback(int tag, size_t size, int sizeIdx)
  15. {
  16. Y_UNUSED(sizeIdx);
  17. static const size_t STACK_FRAMES_COUNT = 32;
  18. static const size_t STACK_FRAMES_SKIP = 1;
  19. void* frames[STACK_FRAMES_COUNT];
  20. size_t frameCount = BackTrace(frames, Y_ARRAY_SIZE(frames));
  21. if (frameCount <= STACK_FRAMES_SKIP) {
  22. return -1;
  23. }
  24. void** stack = &frames[STACK_FRAMES_SKIP];
  25. frameCount -= STACK_FRAMES_SKIP;
  26. auto& collector = AllocationStackCollector();
  27. return collector.Alloc(stack, frameCount, tag, size);
  28. }
  29. void DeallocationCallback(int stackId, int tag, size_t size, int sizeIdx)
  30. {
  31. Y_UNUSED(tag);
  32. Y_UNUSED(sizeIdx);
  33. auto& collector = AllocationStackCollector();
  34. collector.Free(stackId, size);
  35. }
  36. } // namespace
  37. ////////////////////////////////////////////////////////////////////////////////
  38. bool StartAllocationSampling(bool profileAllThreads)
  39. {
  40. auto& collector = AllocationStackCollector();
  41. collector.Clear();
  42. NAllocDbg::SetProfileAllThreads(profileAllThreads);
  43. NAllocDbg::SetAllocationCallback(AllocationCallback);
  44. NAllocDbg::SetDeallocationCallback(DeallocationCallback);
  45. NAllocDbg::SetAllocationSamplingEnabled(true);
  46. return true;
  47. }
  48. bool StopAllocationSampling(IAllocationStatsDumper &out, int count)
  49. {
  50. NAllocDbg::SetAllocationCallback(nullptr);
  51. NAllocDbg::SetDeallocationCallback(nullptr);
  52. NAllocDbg::SetAllocationSamplingEnabled(false);
  53. auto& collector = AllocationStackCollector();
  54. collector.Dump(count, out);
  55. return true;
  56. }
  57. bool StopAllocationSampling(IOutputStream& out, int count) {
  58. TAllocationStatsDumper dumper(out);
  59. return StopAllocationSampling(dumper, count);
  60. }
  61. } // namespace NProfiler