Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #import "Utils.h"
  2. #import <mach/mach.h>
  3.  
  4. @interface Utils ()
  5.  
  6. @end
  7.  
  8. @implementation Utils
  9.  
  10. // 获取CPU占用率
  11. + (float)getCpuUsage
  12. {
  13. kern_return_t kr;
  14. task_info_data_t tinfo;
  15. mach_msg_type_number_t task_info_count;
  16.  
  17. task_info_count = TASK_INFO_MAX;
  18. kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
  19. if (kr != KERN_SUCCESS) {
  20. return -1;
  21. }
  22.  
  23. task_basic_info_t basic_info;
  24. thread_array_t thread_list;
  25. mach_msg_type_number_t thread_count;
  26.  
  27. thread_info_data_t thinfo;
  28. mach_msg_type_number_t thread_info_count;
  29.  
  30. thread_basic_info_t basic_info_th;
  31. uint32_t stat_thread = 0; // Mach threads
  32.  
  33. basic_info = (task_basic_info_t)tinfo;
  34.  
  35. // get threads in the task
  36. kr = task_threads(mach_task_self(), &thread_list, &thread_count);
  37. if (kr != KERN_SUCCESS) {
  38. return -1;
  39. }
  40. if (thread_count > 0)
  41. stat_thread += thread_count;
  42.  
  43. long tot_sec = 0;
  44. long tot_usec = 0;
  45. float tot_cpu = 0;
  46. int j;
  47.  
  48. for (j = 0; j < thread_count; j++)
  49. {
  50. thread_info_count = THREAD_INFO_MAX;
  51. kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
  52. (thread_info_t)thinfo, &thread_info_count);
  53. if (kr != KERN_SUCCESS) {
  54. return -1;
  55. }
  56.  
  57. basic_info_th = (thread_basic_info_t)thinfo;
  58.  
  59. if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
  60. tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
  61. tot_usec = tot_usec + basic_info_th->user_time.microseconds + basic_info_th->system_time.microseconds;
  62. tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0;
  63. }
  64.  
  65. } // for each thread
  66.  
  67. kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
  68. assert(kr == KERN_SUCCESS);
  69.  
  70. return tot_cpu;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement