Created
April 9, 2012 09:03
-
-
Save bxshi/2342427 to your computer and use it in GitHub Desktop.
Get CPU usage by precentage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* ===================================================================================== | |
* | |
* Filename: sys_usage.c | |
* | |
* Description: get usage of CPU and I/O | |
* | |
* Version: 1.0 | |
* Created: 04/09/2012 02:23:08 PM | |
* Revision: none | |
* Compiler: gcc | |
* | |
* Author: YOUR NAME (), | |
* Organization: | |
* | |
* ===================================================================================== | |
*/ | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
struct cpu_stat{ | |
unsigned long user; | |
unsigned long nice; | |
unsigned long sys; | |
unsigned long idle; | |
unsigned long iowait; | |
unsigned long irq; | |
unsigned long softirq; | |
}; | |
struct cpu_stat get_cpu_stat() | |
{ | |
FILE *file; | |
char cpu[4]; | |
struct cpu_stat stat; | |
file = fopen("/proc/stat", "r"); | |
fscanf(file, "%4s %ld %ld %ld %ld %ld %ld %ld", cpu, | |
&stat.user, &stat.nice, &stat.sys, &stat.idle, | |
&stat.iowait, &stat.irq, &stat.softirq); | |
fclose(file); | |
return stat; | |
} | |
void print_cpu_stat(struct cpu_stat stat) | |
{ | |
printf("user:%ld nice:%ld sys:%ld idle:%ld iowait:%ld irq:%ld softirq:%ld\n", stat.user, stat.nice, stat.sys, stat.idle, stat.iowait, stat.irq, stat.softirq); | |
} | |
void print_cpu_usage(struct cpu_stat pre, struct cpu_stat after) | |
{ | |
float total; | |
float idle; | |
total = after.user+after.nice+after.sys+after.idle+after.iowait+after.irq+after.softirq - | |
(pre.user + pre.nice + pre.sys + pre.idle + pre.iowait + pre.irq + pre.softirq); | |
idle = after.idle - pre.idle; | |
printf("CPU usage is %.2f\n", (total-idle) / total * 100); | |
} | |
int main(int argc, char ** argv) | |
{ | |
struct cpu_stat pre, after; | |
pre = get_cpu_stat(); | |
while(1){ | |
sleep(1); | |
after = get_cpu_stat(); | |
print_cpu_usage(pre, after); | |
pre = after; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment