sysinfomacimpl.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "sysinfomacimpl.h"
  2. #include <mach/mach_host.h>
  3. #include <mach/mach_init.h>
  4. #include <mach/mach_types.h>
  5. #include <mach/vm_map.h>
  6. #include <mach/vm_statistics.h>
  7. SysInfoMacImpl::SysInfoMacImpl() : SysInfo() {}
  8. void SysInfoMacImpl::init() { mCpuLoadLastValues = cpuRawData(); }
  9. double SysInfoMacImpl::cpuLoadAverage() {
  10. QVector<qulonglong> firstSample = mCpuLoadLastValues;
  11. QVector<qulonglong> secondSample = cpuRawData();
  12. mCpuLoadLastValues = secondSample;
  13. double overall = (secondSample[0] - firstSample[0]) +
  14. (secondSample[1] - firstSample[1]) +
  15. (secondSample[2] - firstSample[2]);
  16. double total = overall + (secondSample[3] - firstSample[3]);
  17. double percent = (overall / total) * 100.0;
  18. return qBound(0.0, percent, 100.0);
  19. }
  20. /**
  21. * @brief SysInfoMacImpl::memoryUsed 系统内存使用
  22. * @return 百分比
  23. */
  24. double SysInfoMacImpl::memoryUsed() {
  25. vm_size_t pageSize;
  26. vm_statistics64_data_t vmStats;
  27. // A machPort is a kind of special connection to the kernel that
  28. // enables us to request information about the system.
  29. mach_port_t machPort = mach_host_self();
  30. mach_msg_type_number_t count = sizeof(vmStats) / sizeof(natural_t);
  31. host_page_size(machPort, &pageSize);
  32. host_statistics64(machPort, HOST_VM_INFO, (host_info64_t)&vmStats, &count);
  33. qulonglong freeMemory = (int64_t)vmStats.free_count * (int64_t)pageSize;
  34. qulonglong totalMemoryUsed =
  35. ((int64_t)vmStats.active_count + (int64_t)vmStats.inactive_count +
  36. (int64_t)vmStats.wire_count) *
  37. (int64_t)pageSize;
  38. qulonglong totalMemory = freeMemory + totalMemoryUsed;
  39. double percent = (double)totalMemoryUsed / (double)totalMemory * 100.0;
  40. return qBound(0.0, percent, 100.0);
  41. }
  42. QVector<qulonglong> SysInfoMacImpl::cpuRawData() {
  43. host_cpu_load_info_data_t cpuInfo;
  44. mach_msg_type_number_t cpuCount = HOST_CPU_LOAD_INFO_COUNT;
  45. QVector<qulonglong> rawData;
  46. qulonglong totalUser = 0, totalUserNice = 0, totalSystem = 0, totalIdle = 0;
  47. host_statistics64(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpuInfo,
  48. &cpuCount);
  49. for (unsigned int i = 0; i < cpuCount; i++) {
  50. unsigned int maxTicks = CPU_STATE_MAX * i;
  51. totalUser += cpuInfo.cpu_ticks[maxTicks + CPU_STATE_USER];
  52. totalUserNice += cpuInfo.cpu_ticks[maxTicks + CPU_STATE_SYSTEM];
  53. totalSystem += cpuInfo.cpu_ticks[maxTicks + CPU_STATE_NICE];
  54. totalIdle += cpuInfo.cpu_ticks[maxTicks + CPU_STATE_IDLE];
  55. }
  56. rawData.append(totalUser);
  57. rawData.append(totalUserNice);
  58. rawData.append(totalSystem);
  59. rawData.append(totalIdle);
  60. return rawData;
  61. }