Skip to content

Commit

Permalink
[Utils/Memory] Added memory profiling capabilities
Browse files Browse the repository at this point in the history
- Overloaded most of the new & delete operators to hook Tracy's memory profiling
  • Loading branch information
Razakhel committed Jan 21, 2025
1 parent 0c5aa96 commit 40d66e1
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,7 @@ if (RAZ_USE_PROFILING)
message(STATUS "[RaZ] Profiling ENABLED")
else ()
message(STATUS "[RaZ] Profiling DISABLED")
list(REMOVE_ITEM RAZ_FILES "${PROJECT_SOURCE_DIR}/src/RaZ/Utils/Memory.cpp")
endif ()

target_link_libraries(RaZ PRIVATE fastgltf simdjson stb)
Expand Down
69 changes: 69 additions & 0 deletions src/RaZ/Utils/Memory.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#include <tracy/Tracy.hpp>

// See https://en.cppreference.com/w/cpp/memory/new/operator_new

void* operator new(std::size_t size) {
size = std::max(static_cast<std::size_t>(1), size);

if (void* ptr = std::malloc(size)) {
TracyAlloc(ptr, size);
return ptr;
}

throw std::bad_alloc();
}

void* operator new(std::size_t size, const std::nothrow_t&) noexcept {
try {
return operator new(size);
} catch (...) {
return nullptr;
}
}

void* operator new[](std::size_t size) {
size = std::max(static_cast<std::size_t>(1), size);

if (void* ptr = std::malloc(size)) {
TracyAlloc(ptr, size);
return ptr;
}

throw std::bad_alloc();
}

void* operator new[](std::size_t size, const std::nothrow_t&) noexcept {
try {
return operator new[](size);
} catch (...) {
return nullptr;
}
}

// See https://en.cppreference.com/w/cpp/memory/new/operator_delete

void operator delete(void* ptr) noexcept {
TracyFree(ptr);
std::free(ptr);
}

void operator delete(void* ptr, std::size_t) noexcept {
operator delete(ptr);
}

void operator delete(void* ptr, const std::nothrow_t&) noexcept {
operator delete(ptr);
}

void operator delete[](void* ptr) noexcept {
TracyFree(ptr);
std::free(ptr);
}

void operator delete[](void* ptr, std::size_t) noexcept {
operator delete[](ptr);
}

void operator delete[](void* ptr, const std::nothrow_t&) noexcept {
operator delete[](ptr);
}

0 comments on commit 40d66e1

Please sign in to comment.