Created
June 3, 2022 06:31
-
-
Save forrestthewoods/9f0cbab6f05f0228bbed6e8c90e37b58 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <array> | |
#include <chrono> | |
#include <numeric> | |
#include <sstream> | |
#include <thread> | |
#include <vector> | |
using Nanoseconds = std::chrono::nanoseconds; | |
using Microseconds = std::chrono::microseconds; | |
using Milliseconds = std::chrono::milliseconds; | |
using Clock = std::chrono::steady_clock; | |
struct fts_allocator { | |
static void* alloc(const size_t size); | |
static void free(void* ptr); | |
private: | |
static fts_allocator& Get(); | |
fts_allocator(); | |
~fts_allocator(); | |
void* allocInternal(const size_t size); | |
void freeInternal(void* ptr); | |
Clock::time_point _timeBegin; | |
FILE* _file = nullptr; | |
}; | |
void* fts_allocator::alloc(const size_t size) { | |
return Get().allocInternal(size); | |
} | |
void fts_allocator::free(void* ptr) { | |
return Get().freeInternal(ptr); | |
} | |
fts_allocator& fts_allocator::Get() { | |
static fts_allocator sAlloc; | |
return sAlloc; | |
} | |
fts_allocator::fts_allocator() { | |
// Initialize time so we can store relative timestamps | |
_timeBegin = Clock::now(); | |
// Open a journal file | |
_file = std::fopen("c:/temp/doom3_journal.txt", "w"); | |
} | |
fts_allocator::~fts_allocator() { | |
// Close the journal | |
std::fclose(_file); | |
_file = nullptr; | |
} | |
void* fts_allocator::allocInternal(const size_t size) { | |
auto allocRelTime = (Clock::now() - _timeBegin); | |
// Perform actual malloc | |
auto ptr = _aligned_malloc(size, 16); | |
// AllocEntry = a allocSize ptr threadId timestamp | |
std::array<char, 256> buf; | |
int len = std::snprintf( | |
buf.data(), | |
buf.size(), | |
"a %lld %p %lu %lld\n", | |
size, ptr, GetCurrentThreadId(), allocRelTime.count()); | |
std::fwrite(buf.data(), 1, len, _file); | |
return ptr; | |
} | |
void fts_allocator::freeInternal(void* ptr) { | |
auto freeRelTime = (Clock::now() - _timeBegin); | |
_aligned_free(ptr); | |
// FreeEntry = f ptr threadId timestamp | |
std::array<char, 256> buf; | |
int len = std::snprintf( | |
buf.data(), | |
buf.size(), | |
"f %p %lu %lld\n", | |
ptr, GetCurrentThreadId(), freeRelTime.count()); | |
std::fwrite(buf.data(), 1, len, _file); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment