How to determine CPU and memory consumption from inside a process?

后端 未结 9 1797
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 11:28

I once had the task of determining the following performance parameters from inside a running application:

  • Total virtual memory available
  • Virtual memo
9条回答
  •  天命终不由人
    2020-11-21 12:16

    Mac OS X - CPU

    Overall CPU usage:

    From Retrieve system information on MacOS X? :

    #include 
    #include 
    #include 
    #include 
    
    static unsigned long long _previousTotalTicks = 0;
    static unsigned long long _previousIdleTicks = 0;
    
    // Returns 1.0f for "CPU fully pinned", 0.0f for "CPU idle", or somewhere in between
    // You'll need to call this at regular intervals, since it measures the load between
    // the previous call and the current one.
    float GetCPULoad()
    {
       host_cpu_load_info_data_t cpuinfo;
       mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
       if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpuinfo, &count) == KERN_SUCCESS)
       {
          unsigned long long totalTicks = 0;
          for(int i=0; i 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
      _previousTotalTicks = totalTicks;
      _previousIdleTicks  = idleTicks;
      return ret;
    }
    

提交回复
热议问题