In C++, there is no direct functionality to retrieve hardware information. However, with the implementation at the platform level, obtaining hardware information becomes easier. For example, using the Windows system’s windows.h. So how do we retrieve memory usage? You can use the following method:
Memory Information Class Declaration RAMInfo.h:
#pragma once
namespace xm { class RAMInfo final { public: void Update(); float GetUsedRAM() { return m_usedRAM; } float GetFreeRAM() { return m_freeRAM; } float GetMaxRAM() { return m_maxRAM; } private: float m_usedRAM = 0.0f; float m_freeRAM = 0.0f; float m_maxRAM = 0.0f; }; }
Memory Information Class Implementation RAMInfo.cpp:
#include "RAMInfo.h"
#include <Windows.h>
#include <psapi.h>
namespace xm { void RAMInfo::Update() { MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex);
m_maxRAM = statex.ullTotalPhys / 1073741824.f; m_freeRAM = statex.ullAvailPhys / 1073741824.f; m_usedRAM = m_maxRAM - m_freeRAM; }}
Test Code main.cpp:
#include "Core/HardwareInfo/RAMInfo.h"
#include <iostream>
int main() { xm::RAMInfo rawInfo; rawInfo.Update();
std::cout << "Memory Usage: Max(" << rawInfo.GetMaxRAM() << ")GB Used(" << rawInfo.GetUsedRAM() << ")GB Free(" << rawInfo.GetFreeRAM() << ")GB" << std::endl;
return 0; }
Output Result:
