CpuInfo.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "os/c-api/il2cpp-config-platforms.h"
  2. #if IL2CPP_PLATFORM_SUPPORTS_CPU_INFO
  3. #if IL2CPP_TARGET_POSIX && !RUNTIME_TINY
  4. #include "os/CpuInfo.h"
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include "utils/Memory.h"
  8. #include "os/Time.h"
  9. #include "os/Environment.h"
  10. #include <sys/resource.h>
  11. #include <sys/param.h>
  12. #if IL2CPP_TARGET_DARWIN
  13. #include <sys/sysctl.h>
  14. #endif
  15. #include <time.h>
  16. #if IL2CPP_TARGET_LINUX
  17. #include <sys/time.h>
  18. #include <sys/resource.h>
  19. #endif
  20. struct Il2CppCpuUsageState
  21. {
  22. int64_t kernel_time;
  23. int64_t user_time;
  24. int64_t current_time;
  25. };
  26. namespace il2cpp
  27. {
  28. namespace os
  29. {
  30. void* CpuInfo::Create()
  31. {
  32. return IL2CPP_MALLOC_ZERO(sizeof(Il2CppCpuUsageState));
  33. }
  34. int32_t CpuInfo::Usage(void* previous)
  35. {
  36. Il2CppCpuUsageState* prev = (Il2CppCpuUsageState*)previous;
  37. int32_t cpu_usage = 0;
  38. int64_t cpu_total_time;
  39. int64_t cpu_busy_time;
  40. struct rusage resource_usage;
  41. int64_t current_time;
  42. int64_t kernel_time;
  43. int64_t user_time;
  44. if (getrusage(RUSAGE_SELF, &resource_usage) == -1)
  45. {
  46. return -1;
  47. }
  48. current_time = os::Time::GetTicks100NanosecondsMonotonic();
  49. kernel_time = resource_usage.ru_stime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_stime.tv_usec * 10;
  50. user_time = resource_usage.ru_utime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_utime.tv_usec * 10;
  51. cpu_busy_time = (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0));
  52. cpu_total_time = (current_time - (prev ? prev->current_time : 0)) * il2cpp::os::Environment::GetProcessorCount();
  53. if (prev)
  54. {
  55. prev->kernel_time = kernel_time;
  56. prev->user_time = user_time;
  57. prev->current_time = current_time;
  58. }
  59. if (cpu_total_time > 0 && cpu_busy_time > 0)
  60. cpu_usage = (int32_t)(cpu_busy_time * 100 / cpu_total_time);
  61. return cpu_usage;
  62. }
  63. }
  64. }
  65. #endif
  66. #endif