Obtain the CPU usage of a process

Source: Internet
Author: User
Tags filetime

Obtain the CPU usage of a process

 

// Time conversion static _ int64 file_time_2_utc (const filetime * ftime) {large_integer Li; Li. lowpart = ftime-> dwlowdatetime; Li. highpart = ftime-> dwhighdatetime; return Li. quadpart;} // obtain the number of CPU cores. Static int get_processor_number () {system_info Info; getsysteminfo (& info); Return (INT) info. dwnumberofprocessors;} // obtain the process CPU usage int get_cpu_usage (int pid) {// Number of CPUs static int processor_count _ =-1; // last time static _ int6 4 last_time _ = 0; static _ int64 last_system_time _ = 0; filetime now; filetime creation_time; filetime exit_time; filetime kernel_time; filetime user_time; _ int64 system_time; _ int64 time; _ int64 system_time_delta; _ int64 time_delta; int CPU =-1; if (processor_count _ =-1) {processor_count _ = get_processor_number ();} getsystemtimeasfiletime (& now ); handle hprocess = OpenProcess (process_all_a Ccess, false, pid); If (! Getprocesstimes (hprocess, & creation_time, & exit_time, & kernel_time, & user_time) {return-1;} system_time = (bytes (& kernel_time) + file_time_2_utc (& user_time )) /processor_count _; time = file_time_2_utc (& now); If (last_system_time _ = 0) | (last_time _ = 0) {last_system_time _ = system_time; last_time _ = time; Return-1;} system_time_delta = system_time-last_system_time _; time_delta = Time-last_time _; If (time_delta = 0) Return-1; CPU = (INT) (system_time_delta * 100 + time_delta/2)/time_delta); last_system_time _ = system_time; last_time _ = time; return CPU ;}

 

Obtain the CPU usage of a process

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.