简体   繁体   English

C中的CPU使用率(百分比)

[英]CPU usage in C (as percentage)

How can I get CPU usage as percentage using C? 如何使用C获得CPU使用率百分比?

I have a function like this: 我有一个这样的功能:

static int cpu_usage (lua_State *L) {
    clock_t clock_now      = clock();
    double  cpu_percentage = ((double) (clock_now - program_start)) / get_cpus() / CLOCKS_PER_SEC;

    lua_pushnumber(L,cpu_percentage);
    return 1;
}

"program_start" is a clock_t that I use when the program starts. “ program_start”是我在程序启动时使用的clock_t。

Another try: 另一种尝试:

static int cpu_usage(lua_State *L) {
    struct rusage ru;
    getrusage(RUSAGE_SELF, &ru);

    lua_pushnumber(L,ru.ru_utime.tv_sec);
    return 1;
}

Is there any way to measure CPU? 有什么方法可以测量CPU? If I call this function from time to time it keeps returning me the increasing time... but that´s not what I want. 如果我不时调用此函数,它将使我不断增加的时间……但这不是我想要的。

PS: I'm using Ubuntu. PS:我正在使用Ubuntu。

Thank you! 谢谢! =) =)

Your function should work as expected. 您的功能应该可以正常工作。 From clock clock

The clock() function shall return the implementation's best approximation to the processor time used by the process since the beginning of an implementation-defined era related only to the process invocation. 自实现定义的时代的开始(仅与流程调用有关)开始,clock()函数应将实现的最佳近似返回到流程使用处理器时间

This means, it returns the CPU time for this process. 这意味着它将返回此过程的CPU时间。


If you want to calculate the CPU time relative to the wall clock time, you must do the same with gettimeofday . 如果要计算相对于墙上时钟时间的CPU时间,则必须对gettimeofday进行相同的操作。 Save the time at program start 节省程序启动时间

struct timeval wall_start;
gettimeofday(&wall_start, NULL);

and when you want to calculate the percentage 当你想计算百分比

struct timeval wall_now;
gettimeofday(&wall_now, NULL);

Now you can calculate the difference of wall clock time and you get 现在您可以计算挂钟时间的差,您将得到

double start = wall_start.tv_sec + wall_start.tv_usec / 1000000;
double stop = wall_now.tv_sec + wall_now.tv_usec / 1000000;
double wall_time = stop - start;
double cpu_time = ...;
double percentage = cpu_time / wall_time;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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