windows內存監控

#include <thread>
#include <Windows.h>
#include <Psapi.h>
#pragma comment(lib , "psapi.lib")
#include "Common/LogInf.h"
#include "thread.h"

class MemoryWatcher : public CThread
{
public:
    MemoryWatcher();
    ~MemoryWatcher();
    bool startWatch();
    bool stopWatch();
private:
    virtual void Run();
    bool bWantStop = false;
    HANDLE m_hProcess ;
    PROCESS_MEMORY_COUNTERS pmc;
    int m_cnt = 0;
};

bool MemoryWatcher::startWatch() {
    return this->Start();
}

bool MemoryWatcher::stopWatch() {
    bWantStop = true;
    return this->Wait();
}

void MemoryWatcher::Run() {
    while (!bWantStop) {
        if (++m_cnt == 20) {
            GetProcessMemoryInfo(m_hProcess, &pmc, sizeof(pmc));
            LOG_I("當前內存佔用:%dMB 峯值內存佔用:%dMB ", pmc.WorkingSetSize >> 20, pmc.PeakWorkingSetSize >> 20);
            m_cnt = 0;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}

MemoryWatcher *watcher = nullptr;

MemoryWatcher::MemoryWatcher()
{
    m_hProcess = GetCurrentProcess();
}

MemoryWatcher::~MemoryWatcher()
{
}

void StartMemWatch() {
    if (watcher == nullptr) {
        watcher = new MemoryWatcher;
    }
    watcher->startWatch();
}

void StopMemWatch() {
    if (watcher != nullptr) {
        watcher->stopWatch();
    }
    delete watcher;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章