CPU 사용율 구하기(1)
참조 : directfb예제중 df_cpuload.c 를 이용.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <gtk/gtk.h>
#define SET_IF_DESIRED(x,y) do{ if(x) *(x) = (y); }while(0)
#define JT unsigned long
static void four_cpu_numbers(int *uret, int *nret, int *sret, int *iret);
static int get_load();
void* cpu_load(int t);
GThread *adc_insert_thrs;
GError *adc_error;
static void four_cpu_numbers(int *uret, int *nret, int *sret, int *iret)
{
int tmp_u, tmp_n, tmp_s, tmp_i;
static JT old_u, old_n, old_s, old_i, old_wa, old_hi, old_si;
JT new_u, new_n, new_s, new_i, new_wa = 0, new_hi = 0, new_si = 0;
JT ticks_past; /* avoid div-by-0 by not calling too often :-( */
char dummy[16];
FILE *stat;
stat = fopen ("/proc/stat", "r");
if (!stat)
return;
if (fscanf (stat, "%s %lu %lu %lu %lu %lu %lu %lu", dummy,
&new_u, &new_n, &new_s, &new_i, &new_wa, &new_hi, &new_si) < 5)
{
fclose (stat);
return;
}
fclose (stat);
ticks_past = ((new_u + new_n + new_s + new_i + new_wa + new_hi + new_si) -
(old_u + old_n + old_s + old_i + old_wa + old_hi + old_si));
if (ticks_past) {
tmp_u = ((new_u - old_u) << 16) / ticks_past;
tmp_n = ((new_n - old_n) << 16) / ticks_past;
tmp_s = ((new_s - old_s) << 16) / ticks_past;
tmp_i = ((new_i - old_i) << 16) / ticks_past;
}
else {
tmp_u = 0;
tmp_n = 0;
tmp_s = 0;
tmp_i = 0;
}
SET_IF_DESIRED(uret, tmp_u);
SET_IF_DESIRED(nret, tmp_n);
SET_IF_DESIRED(sret, tmp_s);
SET_IF_DESIRED(iret, tmp_i);
old_u = new_u;
old_n = new_n;
old_s = new_s;
old_i = new_i;
old_wa = new_wa;
old_hi = new_hi;
old_si = new_si;
}
#undef JT
static int
get_load()
{
static int old_load = 0;
int u = 0, n = 0, s = 0, i, load;
four_cpu_numbers( &u, &n, &s, &i );
//load = u + n + s;
load = u + n + s + i;
//old_load = (load + load + load + old_load) >> 2;
old_load = ((u+n+s)*100) / (load);
//return old_load >> 10;
return old_load;
}
void* cpu_load(int t)
{
int load;
while(1){
usleep(100000);
load = get_load();
printf("cpu load = %d\n",load);
}
return (void*)0;
}
int main(int argc, char** argv)
{
int load;
g_thread_init(NULL);
adc_insert_thrs = g_thread_create((GThreadFunc)cpu_load,0,TRUE,&adc_error);
g_thread_join(adc_insert_thrs );
/*
while(1){
usleep(100000);
load = get_load();
printf("cpu load = %d\n",load);
}
//*/
return 0;
}