memory_detect.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #ifdef _WIN32
  4. // clang-format off
  5. #include <windows.h>
  6. #include <sysinfoapi.h>
  7. // clang-format on
  8. #else
  9. #include <sys/types.h>
  10. #if defined(__APPLE__) || defined(__FreeBSD__)
  11. #include <sys/sysctl.h>
  12. #elif defined(__linux__)
  13. #include <sys/sysinfo.h>
  14. #else
  15. #include <unistd.h>
  16. #endif
  17. #endif
  18. #include "common/memory_detect.h"
  19. namespace Common {
  20. // Detects the RAM and Swapfile sizes
  21. static MemoryInfo Detect() {
  22. MemoryInfo mem_info{};
  23. #ifdef _WIN32
  24. MEMORYSTATUSEX memorystatus;
  25. memorystatus.dwLength = sizeof(memorystatus);
  26. GlobalMemoryStatusEx(&memorystatus);
  27. mem_info.TotalPhysicalMemory = memorystatus.ullTotalPhys;
  28. mem_info.TotalSwapMemory = memorystatus.ullTotalPageFile - mem_info.TotalPhysicalMemory;
  29. #elif defined(__APPLE__)
  30. u64 ramsize;
  31. struct xsw_usage vmusage;
  32. std::size_t sizeof_ramsize = sizeof(ramsize);
  33. std::size_t sizeof_vmusage = sizeof(vmusage);
  34. // hw and vm are defined in sysctl.h
  35. // https://github.com/apple/darwin-xnu/blob/master/bsd/sys/sysctl.h#L471
  36. // sysctlbyname(const char *, void *, size_t *, void *, size_t);
  37. sysctlbyname("hw.memsize", &ramsize, &sizeof_ramsize, nullptr, 0);
  38. sysctlbyname("vm.swapusage", &vmusage, &sizeof_vmusage, nullptr, 0);
  39. mem_info.TotalPhysicalMemory = ramsize;
  40. mem_info.TotalSwapMemory = vmusage.xsu_total;
  41. #elif defined(__FreeBSD__)
  42. u_long physmem, swap_total;
  43. std::size_t sizeof_u_long = sizeof(u_long);
  44. // sysctlbyname(const char *, void *, size_t *, const void *, size_t);
  45. sysctlbyname("hw.physmem", &physmem, &sizeof_u_long, nullptr, 0);
  46. sysctlbyname("vm.swap_total", &swap_total, &sizeof_u_long, nullptr, 0);
  47. mem_info.TotalPhysicalMemory = physmem;
  48. mem_info.TotalSwapMemory = swap_total;
  49. #elif defined(__linux__)
  50. struct sysinfo meminfo;
  51. sysinfo(&meminfo);
  52. mem_info.TotalPhysicalMemory = meminfo.totalram;
  53. mem_info.TotalSwapMemory = meminfo.totalswap;
  54. #else
  55. mem_info.TotalPhysicalMemory = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE);
  56. mem_info.TotalSwapMemory = 0;
  57. #endif
  58. return mem_info;
  59. }
  60. const MemoryInfo& GetMemInfo() {
  61. static MemoryInfo mem_info = Detect();
  62. return mem_info;
  63. }
  64. } // namespace Common