1. 程式人生 > 其它 >getrusage的用法(檢視記憶體使用情況)

getrusage的用法(檢視記憶體使用情況)

https://blog.csdn.net/imred/article/details/50643022

getrusage - get resource usage,該函式可以程式統計對系統資源的使用量。(實際上是統計了程序執行直到呼叫該函式時的資源用量,如果在不同的時間呼叫該函式,會得到不同的結果)

#include <unistd.h>
#include <sys/resource.h>

void* MemoryTraceFunc(void*) {
#ifndef WIN32
  while (true) {
    rusage usage;
    getrusage(RUSAGE_SELF, &usage);
    int ru_maxrss = static_cast<int>(usage.ru_maxrss / 1024 ); //MB

    std::cout << "MemUse now: " << ru_maxrss << " MB." << std::endl;

    usleep(1000000);
  }
#else
  while (true) {
    PROCESS_MEMORY_COUNTERS info;
    GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) );
    nimbus::DataVar::procise_peak_used_memory_ = info.PeakWorkingSetSize / 1024 / 1024;
    nimbus::DataVar::current_used_memory_ = info.WorkingSetSize / 1024 / 1024;

    if (! nimbus::DataVar::cmd_started_)
      nimbus::DataVar::cmd_peak_used_memory_ = nimbus::DataVar::current_used_memory_;
    else if (nimbus::DataVar::cmd_peak_used_memory_ < nimbus::DataVar::current_used_memory_)
      nimbus::DataVar::cmd_peak_used_memory_ = nimbus::DataVar::current_used_memory_;
    Sleep(1);
  }
#endif
  return NULL;
}