1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use parsers::{map_result, parse_usize};
use nom::{space};
use std::str::{self, FromStr};
use std::io::{Result};
use std::fs;
use std::cmp;
use std::ops::Div;
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct Cpu {
pub cpuid: String,
pub user: usize,
pub nice: usize,
pub system: usize,
pub idle: usize,
pub iowait: usize,
pub irq: usize,
pub softirq: usize,
pub steal: usize,
pub guest: usize,
pub guest_nice: usize,
}
named!(parse_string_field<String>,
map_res!(map_res!(is_not!(" "), str::from_utf8), FromStr::from_str));
named!(parse_cpu_info<Cpu>,
do_parse!(
cpuid: parse_string_field >> space >>
user: parse_usize >> space >>
nice: parse_usize >> space >>
system: parse_usize >> space >>
idle: parse_usize >> space >>
iowait: parse_usize >> space >>
irq: parse_usize >> space >>
softirq: parse_usize >> space >>
steal: parse_usize >> space >>
guest: parse_usize >> space >>
guest_nice: parse_usize >>
(Cpu {
cpuid: cpuid,
user: user,
nice: nice,
system: system,
idle: idle,
iowait: iowait,
irq: irq,
softirq: softirq,
steal: steal,
guest: guest,
guest_nice: guest_nice,
} )));
pub fn cpu_line_aggregated_entry() -> Result<Cpu> {
let data = fs::read_to_string("/proc/stat")?;
let lines: Vec<&str> = data.lines().collect();
let cpu_line_info = try!(map_result(parse_cpu_info(lines[0].as_bytes())));
Ok(cpu_line_info)
}
pub fn cpu_count() -> Result<usize> {
let data = fs::read_to_string("/proc/stat")?;
let lines: Vec<&str> = data.lines().collect();
let mut cpus = 0;
for line in lines {
if line.starts_with("cpu") {
cpus += 1;
}
}
Ok(cmp::max(cpus - 1, 1))
}
pub fn cpu_period() -> Result<usize> {
let cpu = cpu_line_aggregated_entry().unwrap();
let total_time = cpu.user + cpu.nice + cpu.system + cpu.irq + cpu.softirq +
cpu.idle + cpu.iowait + cpu.steal + cpu.guest + cpu.guest_nice;
let cpu_count = cpu_count().unwrap();
Ok(total_time.div(cpu_count))
}
#[cfg(test)]
pub mod tests {
pub use pid::cpu::{Cpu};
use pid::cpu::parse_cpu_info;
#[test]
fn test_parse_cpu_time_info_entry() {
let entry =
b"cpu0 49663 0 40234 104757317 542691 4420 39572 0 0 0";
let got_mi = parse_cpu_info(entry).unwrap().1;
let want_mi = Cpu {
cpuid: "cpu0".to_string(),
user: 49663,
nice: 0,
system: 40234,
idle: 104757317,
iowait: 542691,
irq: 4420,
softirq: 39572,
steal: 0,
guest: 0,
guest_nice : 0,
};
assert_eq!(got_mi, want_mi);
}
}