ensure operation is using double
[psensor.git] / src / lib / cpu.c
1 /*
2  * Copyright (C) 2010-2014 jeanfi@gmail.com
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301 USA
18  */
19 #include <locale.h>
20 #include <libintl.h>
21 #define _(str) gettext(str)
22
23 #include <string.h>
24
25 #include <glibtop/cpu.h>
26
27 #include "cpu.h"
28
29 static float last_used;
30 static float last_total;
31
32 struct psensor *create_cpu_usage_sensor(int measures_len)
33 {
34         char *label;
35         int type;
36         char *id;
37         struct psensor *psensor;
38
39         id = strdup("cpu usage");
40         label = strdup("cpu usage");
41         type = SENSOR_TYPE_GTOP | SENSOR_TYPE_CPU_USAGE;
42
43         psensor = psensor_create(id,
44                                  label,
45                                  strdup(_("CPU")),
46                                  type,
47                                  measures_len);
48
49         return psensor;
50 }
51
52 struct psensor * *
53 cpu_psensor_list_add(struct psensor **sensors, int measures_len)
54 {
55         struct psensor *s;
56
57         s = create_cpu_usage_sensor(measures_len);
58
59         return psensor_list_add(sensors, s);
60 }
61
62 static double get_usage()
63 {
64         glibtop_cpu cpu;
65         unsigned long int used;
66         unsigned long int dt;
67         double cpu_rate;
68
69         glibtop_get_cpu(&cpu);
70
71         used = cpu.user + cpu.nice + cpu.sys;
72
73         dt = cpu.total - last_total;
74
75         if (dt)
76                 cpu_rate = 100.0 * (used - last_used) / dt;
77         else
78                 cpu_rate = UNKNOWN_DBL_VALUE;
79
80         last_used = used;
81         last_total = cpu.total;
82
83         return cpu_rate;
84 }
85
86 void cpu_usage_sensor_update(struct psensor *s)
87 {
88         psensor_set_current_value(s, get_usage());
89 }
90
91 void cpu_psensor_list_update(struct psensor **sensors)
92 {
93         struct psensor *s;
94
95         while (*sensors) {
96                 s = *sensors;
97
98                 if (s->type & SENSOR_TYPE_GTOP
99                     && s->type & SENSOR_TYPE_CPU_USAGE)
100                         cpu_usage_sensor_update(s);
101
102                 sensors++;
103         }
104 }