windows内存监控

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/how0723/article/details/84027482
#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;
}

猜你喜欢

转载自blog.csdn.net/how0723/article/details/84027482