You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.0 KiB

3 months ago
  1. /*
  2. * Author: David Robert Nadeau
  3. * Site: http://NadeauSoftware.com/
  4. * License: Creative Commons Attribution 3.0 Unported License
  5. * http://creativecommons.org/licenses/by/3.0/deed.en_US
  6. */
  7. /*
  8. * Modified by Tom van Dijk to remove WIN32 and solaris code
  9. */
  10. #if defined(__APPLE__) && defined(__MACH__)
  11. #include <unistd.h>
  12. #include <sys/resource.h>
  13. #include <mach/mach.h>
  14. #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
  15. #include <unistd.h>
  16. #include <sys/resource.h>
  17. #include <stdio.h>
  18. #else
  19. #error "Cannot define getPeakRSS( ) or getCurrentRSS( ) for an unknown OS."
  20. #endif
  21. /**
  22. * Returns the peak (maximum so far) resident set size (physical
  23. * memory use) measured in bytes, or zero if the value cannot be
  24. * determined on this OS.
  25. */
  26. size_t
  27. getPeakRSS()
  28. {
  29. struct rusage rusage;
  30. getrusage(RUSAGE_SELF, &rusage);
  31. #if defined(__APPLE__) && defined(__MACH__)
  32. return (size_t)rusage.ru_maxrss;
  33. #else
  34. return (size_t)(rusage.ru_maxrss * 1024L);
  35. #endif
  36. }
  37. /**
  38. * Returns the current resident set size (physical memory use) measured
  39. * in bytes, or zero if the value cannot be determined on this OS.
  40. */
  41. size_t
  42. getCurrentRSS()
  43. {
  44. #if defined(__APPLE__) && defined(__MACH__)
  45. /* OSX ------------------------------------------------------ */
  46. struct mach_task_basic_info info;
  47. mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
  48. if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &infoCount) != KERN_SUCCESS)
  49. return (size_t)0L; /* Can't access? */
  50. return (size_t)info.resident_size;
  51. #else
  52. /* Linux ---------------------------------------------------- */
  53. long rss = 0L;
  54. FILE *fp = NULL;
  55. if ((fp = fopen("/proc/self/statm", "r")) == NULL)
  56. return (size_t)0L; /* Can't open? */
  57. if (fscanf(fp, "%*s%ld", &rss) != 1) {
  58. fclose(fp);
  59. return (size_t)0L; /* Can't read? */
  60. }
  61. fclose(fp);
  62. return (size_t)rss * (size_t)sysconf(_SC_PAGESIZE);
  63. #endif
  64. }