在c程序中获得memory使用情况

#include <sys/resource.h>
#define PRINT(...) fprintf(stderr, __VA_ARGS__)
void mem_usage() {
  struct rusage r_usage;
  getrusage(RUSAGE_SELF, &r_usage);
  PRINT("gputrigger-> current Memory usage: %ld KB\n", r_usage.ru_maxrss);
}

在cpp程序中获得memory使用情况

当然也可以直接使用c程序的方法

#include <unistd.h>
#include <string>
#include <fstream>
#include <ios>
#include <iostream>

void mem_usage() {
  using std::ifstream;
  using std::ios_base;
  using std::string;
  double vm_usage = 0.0;
  double resident_set = 0.0;
  ifstream stat_stream("/proc/self/stat", ios_base::in);  // get info from proc
  // create some variables to get info
  string pid,comm, state, ppid, pgrp, session, tty_nr;
  string tpgid, flags, minflt, cminflt, majflt, cmajflt;
  string utime, stime, cutime, cstime, priority, nice;
  string O, itrealvalue, starttime;
  unsigned long vsize;
  long rss;
  stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt >> utime >> stime >> cutime >> cstime >> priority >> nice >> O >> itrealvalue >> starttime >> vsize >> rss;
  stat_stream.close();
  long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024;
  vm_usage = vsize / 1024.0;
  resident_set = rss * page_size_kb;
  std::cout << "debug-> VM: " << vm_usage << "kb; RSS: " << resident_set << "kb" << std::endl;

}   

zsh 使用time打印更多信息

https://www.findhao.net/easycoding/2593.html

Reference

https://superuser.com/questions/480928/is-there-any-command-like-time-but-for-memory-usage

https://cppsecrets.com/users/41129711010797106994610011511264103109971051084699111109/C-program-to-get-memory-usage.php

https://stackoverflow.com/questions/1558402/memory-usage-of-current-process-in-c

https://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-runtime-using-c#comment484943_671389


文章版权归 FindHao 所有丨本站默认采用CC-BY-NC-SA 4.0协议进行授权|
转载必须包含本声明,并以超链接形式注明作者 FindHao 和本文原始地址:
https://findhao.net/easycoding/2594.html

Comments