1. #if defined(__APPLE__)
    2. #include <mach/task.h>
    3. #include <mach/mach_init.h>
    4. int64_t Stats::GetMemoryRSS() {
    5. task_t task = MACH_PORT_NULL;
    6. struct task_basic_info t_info;
    7. mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
    8. if (task_for_pid(current_task(), getpid(), &task) != KERN_SUCCESS) return 0;
    9. task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
    10. return static_cast<int64_t>(t_info.resident_size);
    11. }
    12. #else
    13. #include <fcntl.h>
    14. #include <string>
    15. #include <cstdio>
    16. #include <cstring>
    17. int64_t Stats::GetMemoryRSS() {
    18. int fd, count;
    19. char buf[4096], filename[256];
    20. snprintf(filename, sizeof(filename), "/proc/%d/stat", getpid());
    21. if ((fd = open(filename, O_RDONLY)) == -1) return 0;
    22. if (read(fd, buf, sizeof(buf)) <= 0) {
    23. close(fd);
    24. return 0;
    25. }
    26. close(fd);
    27. char *start = buf;
    28. count = 23; // RSS is the 24th field in /proc/<pid>/stat
    29. while (start && count--) {
    30. start = strchr(start, ' ');
    31. if (start) start++;
    32. }
    33. if (!start) return 0;
    34. char *stop = strchr(start, ' ');
    35. if (!stop) return 0;
    36. *stop = '\0';
    37. int rss = std::atoi(start);
    38. return static_cast<int64_t>(rss * sysconf(_SC_PAGESIZE));
    39. }
    40. #endif