1

I am trying to build a function that will return the cpu usage of my vm's processors over a period of 1 second. The goal is to use pretty basic C library function. The method takes 3 arguments: the path, a cpu_stats *prev structure and a cpu_stats *curr structure. Both structures are used to store previous and current values so that the method gets accurate as soon as it ran twice. The problem I seem to have is about accurately returning the value. For now I am adding every value of the first line of /proc/stat and using that as my total value, and taking the value of the 3rd column as my idle value ( no idea if it is this one, different sites different answers about what each column is). Let me know if you know where to start and what to change. For now all the tests my code go through says that my results are always 100.0% but the values expected are like 32.2%/72.1%/49.0%/etc...

Here is my code:

double pfs_cpu_usage(char *proc_dir, struct cpu_stats *prev, struct cpu_stats *curr)
{
    long idleOne, idleTwo, totalOne, totalTwo=0;
    idleOne = prev->idle;
    totalOne = prev->total;
    int fd = open_path(proc_dir, "stat");
    if (fd <= 0) {
        perror("open_path");
        return -1;
}

size_t line_sz = 0;
char line[256];
while ((line_sz = one_lineread(fd, line, 256)) > 0) {
    char *next_tok = line;
    char *curr_tok;
    char *endPtr;
    int counter = 1;
    while ((curr_tok = next_token(&next_tok, "\n\t: ")) != NULL) {
        if(counter == 5) {
           counter++;
           idleTwo = strtol(curr_tok, &endPtr, 32);
           curr->idle = idleTwo;
        }
        else if(strcmp(curr_tok,"cpu") == 0){
            counter++;
        }
        else{
            counter++;
            totalTwo += strtol(curr_tok, &endPtr, 32);
            curr->total = totalTwo;
        }
    }
}
long diffIdle = idleTwo - idleOne;
long diffTotal = totalTwo - totalOne;
double cpuUsage = (1.0 - ((double)diffIdle)*1.0/((double)diffTotal)*100);
close(fd);
return cpuUsage;
}

Here is the first line of my /proc/stat file:

cpu  12836188 17450 280277082 121169501 1538 0 2490 5206 0 0

Apparently, the idle value stored seems off from my debugging.

Yohan
  • 145
  • 1
  • 10

1 Answers1

0

Ok, then this article? https://stackoverflow.com/a/23376195/13307070

This answer based on https://htop.dev/ which using /proc/stat

InYeopTTi
  • 924
  • 6
  • 9
  • I might be wrong but it seems like my code is doing that, I feel like I tried everything but can't figure it out. – Yohan Sep 15 '20 at 00:47