-2

I'm trying to get my program's CPU usage in my code. I used the code below but it returns total CPU usage. Is there a way to get only my program's usage?

int FileHandler;
char FileBuffer[1024];
float load;

FileHandler = open("/proc/loadavg", O_RDONLY);
if(FileHandler < 0) {
  return -1; }
read(FileHandler, FileBuffer, sizeof(FileBuffer) - 1);
sscanf(FileBuffer, "%f", &load);
close(FileHandler);
return (int)(load * 100);
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 2
    Have you looked at:http://stackoverflow.com/questions/1420426/calculating-cpu-usage-of-a-process-in-linux ? – Jakub Jul 17 '14 at 11:10

1 Answers1

0

You can use popen() with ps as command:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

FILE *popen(const char *command, const char *mode);
int pclose(FILE *stream);

int main(void)
{
    FILE *cmd;
    char s[64];
    double cpu;

    sprintf(s, "ps --no-headers -p %d -o %%cpu", (int)getpid());
    cmd = popen(s, "r");
    if (cmd == NULL) {
        perror("popen");
        exit(EXIT_FAILURE);
    }
    if (fgets(s, sizeof(s), cmd) != NULL) {
        cpu = strtod(s, NULL);
        printf("%f\n", cpu);
    }
    pclose(cmd);
    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94