memtrack.hpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #ifndef memtrack_hpp
  2. #define memtrack_hpp
  3. /*
  4. * Author: David Robert Nadeau
  5. * Site: http://NadeauSoftware.com/
  6. * License: Creative Commons Attribution 3.0 Unported License
  7. * http://creativecommons.org/licenses/by/3.0/deed.en_US
  8. */
  9. #include <unistd.h>
  10. #include <sys/resource.h>
  11. #include <stdio.h>
  12. namespace fv_util {
  13. /**
  14. * Returns the peak (maximum so far) resident set size (physical
  15. * memory use) measured in bytes.
  16. */
  17. size_t getPeakRSS() {
  18. struct rusage rusage;
  19. getrusage(RUSAGE_SELF, &rusage);
  20. return (size_t) (rusage.ru_maxrss * 1024L);
  21. }
  22. /**
  23. * Returns the current resident set size (physical memory use) measured
  24. * in bytes.
  25. */
  26. size_t getCurrentRSS() {
  27. long rss = 0L;
  28. FILE *fp = NULL;
  29. if ((fp = fopen("/proc/self/statm", "r")) == NULL)
  30. return (size_t) 0L; /* Can't open? */
  31. if (fscanf(fp, "%*s%ld", &rss) != 1) {
  32. fclose(fp);
  33. return (size_t) 0L; /* Can't read? */
  34. }
  35. fclose(fp);
  36. return (size_t) rss * (size_t) sysconf(_SC_PAGESIZE);
  37. }
  38. } // fv
  39. #endif // memtrack_hpp