added support of cpu usage monitoring
[psensor.git] / src / lib / cpu.c
1 /*
2     Copyright (C) 2010-2011 jeanfi@gmail.com
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU 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
20 #include <locale.h>
21 #include <libintl.h>
22 #define _(str) gettext(str)
23
24 #include <string.h>
25
26 #include <glibtop/cpu.h>
27
28 #include "cpu.h"
29
30 static glibtop_cpu *cpu;
31 static float last_used;
32 static float last_total;
33
34 static struct psensor *create_sensor(int measures_len)
35 {
36         char *label;
37         int type;
38         char *id;
39         struct psensor *psensor;
40
41         id = strdup("cpu usage");
42         label = strdup("cpu usage");
43         type = SENSOR_TYPE_CPU_USAGE;
44
45         psensor = psensor_create(id, label, type, measures_len);
46
47         return psensor;
48 }
49
50 struct psensor * *
51 cpu_psensor_list_add(struct psensor **sensors, int measures_len)
52 {
53         struct psensor *s;
54
55         s = create_sensor(measures_len);
56
57         return psensor_list_add(sensors, s);
58 }
59
60 static double get_usage()
61 {
62         unsigned long int used = 0;
63         unsigned long int dt;
64         double cpu_rate = UNKNOWN_DBL_VALUE;
65
66         if (!cpu)
67                 cpu = malloc(sizeof(glibtop_cpu));
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 * (used - last_used) / dt;
77
78         last_used = used;
79         last_total = cpu->total;
80
81         return cpu_rate;
82 }
83
84 void cpu_psensor_list_update(struct psensor **sensors)
85 {
86         struct psensor **ss, *s;
87
88         ss = sensors;
89         while (*ss) {
90                 s = *ss;
91
92                 if (s->type == SENSOR_TYPE_CPU_USAGE)
93                         psensor_set_current_value(s, get_usage());
94
95                 ss++;
96         }
97 }
98
99 void cpu_cleanup()
100 {
101         if (cpu)
102                 free(cpu);
103 }