code_junkie

How do I programmatically check memory use in a fairly portable way? (C/C++)

Nov 13th, 2011
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. unsigned long m0 = GetMemoryInUse();
  2. char *p = new char[ random_number ];
  3. unsigned long m1 = GetMemoryInUse();
  4. printf( "%d bytes usedn", (m1-m0) );
  5.  
  6. #ifdef __linux__
  7. # include <sys/sysinfo.h>
  8. #endif
  9.  
  10. #ifdef __APPLE__
  11. # include <mach/task.h>
  12. # include <mach/mach_init.h>
  13. #endif
  14.  
  15. #ifdef _WINDOWS
  16. # include <windows.h>
  17. #else
  18. # include <sys/resource.h>
  19. #endif
  20.  
  21. /// The amount of memory currently being used by this process, in bytes.
  22. /// By default, returns the full virtual arena, but if resident=true,
  23. /// it will report just the resident set in RAM (if supported on that OS).
  24. size_t memory_used (bool resident=false)
  25. {
  26. #if defined(__linux__)
  27. // Ugh, getrusage doesn't work well on Linux. Try grabbing info
  28. // directly from the /proc pseudo-filesystem. Reading from
  29. // /proc/self/statm gives info on your own process, as one line of
  30. // numbers that are: virtual mem program size, resident set size,
  31. // shared pages, text/code, data/stack, library, dirty pages. The
  32. // mem sizes should all be multiplied by the page size.
  33. size_t size = 0;
  34. FILE *file = fopen("/proc/self/statm", "r");
  35. if (file) {
  36. unsigned long vm = 0;
  37. fscanf (file, "%ul", &vm); // Just need the first num: vm size
  38. fclose (file);
  39. size = (size_t)vm * getpagesize();
  40. }
  41. return size;
  42. #endif
  43.  
  44. #elif defined(__APPLE__)
  45. // Inspired by:
  46. // http://miknight.blogspot.com/2005/11/resident-set-size-in-mac-os-x.html
  47. struct task_basic_info t_info;
  48. mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
  49. task_info(current_task(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
  50. size_t size = (resident ? t_info.resident_size : t_info.virtual_size);
  51. return size;
  52.  
  53. #elif defined(_WINDOWS)
  54. // According to MSDN...
  55. PROCESS_MEMORY_COUNTERS counters;
  56. if (GetProcessMemoryInfo (GetCurrentProcess(), &count, sizeof (count)))
  57. return count.PagefileUsage;
  58. else return 0;
  59.  
  60. #else
  61. // No idea what platform this is
  62. return 0; // Punt
  63. #endif
  64. }
Add Comment
Please, Sign In to add comment