簡易メモリー使用量計測器

リークしてるんじゃない? ということで、簡単に現時点でのメモリー使用量のスナップショットを取りたくなった。

Linux なら /proc/[pid]/statm を参照するのが簡単だということでこんな感じのユーティリティーを実装。

#include <unistd.h> // for getpid()

#include <memory>
#include <fstream>
#include <sstream>
#include <iostream>

class MemUsage {
public:
  unsigned size, resident, share, text, lib, data, dirty;

  MemUsage() {
    std::auto_ptr<std::istream> is(file_statm());
    *is >> size >> resident >> share >> text >> lib >> data >> dirty;
  }

private:
  static std::istream* file_statm() {
    std::ostringstream os("/proc/");
    os << getpid() << "/statm";
    return new std::ifstream(os.str().c_str());
  }
};

std::ostream& operator<< (std::ostream &os, const MemUsage &mu) {
  return os << "size: " << mu.size << ", RSS: " << mu.resident
    << ", share: " << mu.share << ", text: " << mu.text
    << ", lib: ", << mu.lib << ", data: " << mu.data
    << ", dt: " << mu.dirty;
}

スナップショットを取りたいところで、

  std::cout << MemUsage() << std::endl;

などとしてやればいい。