From 043afd2608364408ea40c9fa87dc77361412ccf6 Mon Sep 17 00:00:00 2001 From: Doug MacEachern Date: Wed, 12 Mar 2008 06:20:43 +0000 Subject: [PATCH] native version of CpuPerc.java --- include/sigar_format.h | 13 +++++++++++++ src/sigar_format.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/include/sigar_format.h b/include/sigar_format.h index a870e6f8..c7b5e131 100644 --- a/include/sigar_format.h +++ b/include/sigar_format.h @@ -19,6 +19,19 @@ #ifndef SIGAR_FORMAT_H #define SIGAR_FORMAT_H +typedef struct { + double user; + double sys; + double nice; + double idle; + double wait; + double combined; +} sigar_cpu_perc_t; + +SIGAR_DECLARE(int) sigar_cpu_perc_calculate(sigar_cpu_t *prev, + sigar_cpu_t *curr, + sigar_cpu_perc_t *perc); + SIGAR_DECLARE(int) sigar_uptime_string(sigar_t *sigar, sigar_uptime_t *uptime, char *buffer, diff --git a/src/sigar_format.c b/src/sigar_format.c index 7f7a4a8a..8cffa9eb 100644 --- a/src/sigar_format.c +++ b/src/sigar_format.c @@ -22,6 +22,7 @@ #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" +#include "sigar_format.h" #include #include @@ -604,3 +605,35 @@ SIGAR_DECLARE(char *)sigar_net_services_name_get(sigar_t *sigar, return NULL; } } + +SIGAR_DECLARE(int) sigar_cpu_perc_calculate(sigar_cpu_t *prev, + sigar_cpu_t *curr, + sigar_cpu_perc_t *perc) +{ + double diff_user, diff_sys, diff_nice, diff_idle, diff_wait, diff_total; + + diff_user = curr->user - prev->user; + diff_sys = curr->sys - prev->sys; + diff_nice = curr->nice - prev->nice; + diff_idle = curr->idle - prev->idle; + diff_wait = curr->wait - prev->wait; + + diff_user = diff_user < 0 ? 0 : diff_user; + diff_sys = diff_sys < 0 ? 0 : diff_sys; + diff_nice = diff_nice < 0 ? 0 : diff_nice; + diff_idle = diff_idle < 0 ? 0 : diff_idle; + diff_wait = diff_wait < 0 ? 0 : diff_wait; + + diff_total = + diff_user + diff_sys + diff_nice + diff_idle + diff_wait; + + perc->user = diff_user / diff_total; + perc->sys = diff_sys / diff_total; + perc->nice = diff_nice / diff_total; + perc->idle = diff_idle / diff_total; + perc->wait = diff_wait / diff_total; + perc->combined = + perc->user + perc->sys + perc->nice + perc->wait; + + return SIGAR_OK; +}