Results 1 to 2 of 2
hi
I am trying to get the average cpu utilization for an hour. but i am facing some problems. right now i am using the mpstat command but that gives ...
- 08-16-2007 #1Linux Newbie
- Join Date
- May 2005
- Location
- Chennai,TamilNadu, India
- Posts
- 141
Cpu Utilization
hi
I am trying to get the average cpu utilization for an hour. but i am facing some problems. right now i am using the mpstat command but that gives the average from the uptime or last boot of the system...
i can execute the command mpstat 3600 but that i will have to wait on a popen and then read call till it finishes
is there any mechanism where i can reset the mpstat values at the end of each hour so that the average gets calculated from scratch again... just like a reboot of a system...??????
or is there any command that will give me the cpu utilization for the past hour..?
- 08-24-2007 #2Linux Newbie
- Join Date
- May 2005
- Location
- Chennai,TamilNadu, India
- Posts
- 141
i found a method to do this...posting it out here if it helps anyone.. basically i went through the mpstat code and did it the same way they were doing...
like if you give mpstat 3600
static int read_proc_stats( unsigned long long *idle, unsigned long long *uptime)
{
static char line[80];
FILE *fp = NULL;
unsigned long long cc_user, cc_nice, cc_system, cc_hardirq, cc_softirq;
unsigned long long cc_idle, cc_iowait, cc_steal;
unsigned long long cc_uptime;
if ((fp = fopen("/proc/stat", "r")) == NULL) {
dbgprint(D_ERR,"Could not open the /proc/stat");
return -1;
}
if(fgets(line, 80, fp) != NULL)
{
if (!strncmp(line, "cpu ", 4))
{
cc_hardirq = cc_softirq = cc_steal = 0;
/* CPU counters became unsigned long long with kernel 2.6.5 */
sscanf(line + 5, "%llu %llu %llu %llu %llu %llu %llu %llu",
&cc_user, &cc_nice, &cc_system, &cc_idle, &cc_iowait, &cc_hardirq, &cc_softirq, &cc_steal);
cc_uptime = cc_user + cc_nice + cc_system + cc_idle + cc_iowait + cc_hardirq +
cc_softirq + cc_steal;
}
}else{
return -1;
}
if(fp)
fclose(fp);
*idle = cc_idle;
*uptime = cc_uptime;
return 0;
}
#define HZ (1024)
#define S_VALUE(m,n,p) (((double) ((n) - (m))) / (p) * HZ)
/* new define to normalize to %; HZ is 1024 on IA64 and % should be normalized to 100 */
#define SP_VALUE(m,n,p) (((double) ((n) - (m))) / (p) * 100)
double ll_sp_value(unsigned long long value1, unsigned long long value2,
unsigned long long itv)
{
if ((value2 < value1) && (value1 <= 0xffffffff))
/* Counter's type was unsigned long and has overflown */
return ((double) ((value2 - value1) & 0xffffffff)) / itv * 100;
else
return SP_VALUE(value1, value2, itv);
}
static int get_cpu_stats ()
{
unsigned long long uptime, uptime1;
unsigned long long idle, idle1;
unsigned long long itv;
double cpu_utils;
read_proc_stats( &idle, &uptime);
sleep(3600);
read_proc_stats( &idle1, &uptime1);
itv = (uptime1 - uptime) & 0xffffffff;
cpu_utils = (idle1 < idle )? 0.0:ll_sp_value( idle, idle1, itv);
cpu_utils = 100 - cpu_utils;
return 0;
}


Reply With Quote
