简体   繁体   中英

How can I calculate the Average CPU usage of every process in C

In need to calculate the total CPU occupy time of process and divide that by the current time minus the process start time.

So far I have the following code:

    #include <linux/time.h>

    cputime_t kernel_time = task_cputime->stime;  //total time running in kernel space
    cputime_t user_time =  task_cputime->utime;  //total time  running in user space
    cputime_t total_occupy = kernel_time + user_time;  //Total CPU occupy time

    //convert to ms
    unsigned long total_occupy_ms = mulhdu(total_occupy, __cputime_msec_factor);

How would I use do_gettimeofday to get current time and task_strcut->real_start_time in ms? It may be easy, but I am fairly new to kernel programming.

struct timeval tv;
unsigned long timeofday_in_ms = 0;
unsigned logn real_start_time_in_ms = 0;
do_gettimeofday(&tv);
timeofday = jiffies_to_ms(timeval_to_jiffies(&tv));
real_start_time = jiffies_to_ms(timespec_to_jiffies(&current->real_start_time));

All the function involving above are self-explanatory and can be used in kernel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM