c - 如何计算C中每个进程的平均CPU使用率

标签 c linux performance linux-kernel kernel

需要计算进程占用CPU的总时间,除以当前时间减去进程启动时间。

到目前为止,我有以下代码:

    #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);

如何使用do_gettimeofday获取当前时间和task_strcut->real_start_time(以毫秒为单位)?这可能很简单,但我对内核编程还很陌生。

最佳答案

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));

以上涉及的所有函数都是不言自明的,可以在内核中使用

关于c - 如何计算C中每个进程的平均CPU使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22672332/

相关文章:

linux - struct stat 时间是 GMT 吗?

c - Eclipse 并行工具平台 (Kepler) 中的 "Type ' MPI_Status ' could not be resolved"

performance - Groovy I/O 性能问题

java - Java 中的优雅降级以避免内存不足错误

linux - Saxon 找不到 "jni.h"文件

javascript - 调用 javascript 函数最快的方法是什么

c - 覆盖 "complex"的定义

使用 strcmp 进行比较

c - scanf 读入的值未按预期运行

c - 如何使用 Bruce 的 C 编译器进行编译以获得在 8086 处理器上运行的 asm 文件