简体   繁体   中英

CPU usage in C (as percentage)

How can I get CPU usage as percentage using C?

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.

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? 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.

Thank you! =)

Your function should work as expected. From 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.

This means, it returns the CPU time for this process.


If you want to calculate the CPU time relative to the wall clock time, you must do the same with 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;

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