Skip to main content

Cpu

Struct Cpu 

Source
pub struct Cpu { /* private fields */ }
Expand description

Contains all the methods of the Cpu struct.

use sysinfo::{System, RefreshKind, CpuRefreshKind};

let mut s = System::new_with_specifics(
    RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
);

// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh CPUs again to get actual value.
s.refresh_cpu_all();

for cpu in s.cpus() {
    println!("{}%", cpu.cpu_usage());
}

Implementations§

Source§

impl Cpu

Source

pub fn cpu_usage(&self) -> f32

Returns this CPU’s usage.

Note: You’ll need to refresh it at least twice (diff between the first and the second is how CPU usage is computed) at first if you want to have a non-zero value.

use sysinfo::{System, RefreshKind, CpuRefreshKind};

let mut s = System::new_with_specifics(
    RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
);

// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh CPUs again to get actual value.
s.refresh_cpu_all();

for cpu in s.cpus() {
    println!("{}%", cpu.cpu_usage());
}
Source

pub fn name(&self) -> &str

Returns this CPU’s name.

use sysinfo::{System, RefreshKind, CpuRefreshKind};

let s = System::new_with_specifics(
    RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
);
for cpu in s.cpus() {
    println!("{}", cpu.name());
}
Examples found in repository?
examples/simple.rs (line 147)
70fn interpret_input(
71    input: &str,
72    sys: &mut System,
73    networks: &mut Networks,
74    disks: &mut Disks,
75    components: &mut Components,
76    users: &mut Users,
77) -> bool {
78    match input.trim() {
79        "help" => print_help(),
80        "refresh_disks" => {
81            println!("Refreshing disk list...");
82            disks.refresh(true);
83            println!("Done.");
84        }
85        "refresh_users" => {
86            println!("Refreshing user list...");
87            users.refresh();
88            println!("Done.");
89        }
90        "refresh_networks" => {
91            println!("Refreshing network list...");
92            networks.refresh(true);
93            println!("Done.");
94        }
95        "refresh_components" => {
96            println!("Refreshing component list...");
97            components.refresh(true);
98            println!("Done.");
99        }
100        "refresh_cpu" => {
101            println!("Refreshing CPUs...");
102            sys.refresh_cpu_all();
103            println!("Done.");
104        }
105        "signals" => {
106            for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107                println!("{:2}:{sig:?}", nb + 1);
108            }
109        }
110        "cpus" => {
111            // Note: you should refresh a few times before using this, so that usage statistics
112            // can be ascertained
113            println!(
114                "number of physical cores: {}",
115                System::physical_core_count()
116                    .map(|c| c.to_string())
117                    .unwrap_or_else(|| "Unknown".to_owned()),
118            );
119            println!("total CPU usage: {}%", sys.global_cpu_usage());
120            for cpu in sys.cpus() {
121                println!("{cpu:?}");
122            }
123        }
124        "memory" => {
125            println!("total memory:     {: >10} KB", sys.total_memory() / 1_000);
126            println!(
127                "available memory: {: >10} KB",
128                sys.available_memory() / 1_000
129            );
130            println!("used memory:      {: >10} KB", sys.used_memory() / 1_000);
131            println!("total swap:       {: >10} KB", sys.total_swap() / 1_000);
132            println!("used swap:        {: >10} KB", sys.used_swap() / 1_000);
133        }
134        "quit" | "exit" => return true,
135        "all" => {
136            for (pid, proc_) in sys.processes() {
137                println!(
138                    "{}:{} status={:?}",
139                    pid,
140                    proc_.name().to_string_lossy(),
141                    proc_.status()
142                );
143            }
144        }
145        "frequency" => {
146            for cpu in sys.cpus() {
147                println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148            }
149        }
150        "vendor_id" => {
151            println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152        }
153        "brand" => {
154            println!("brand: {}", sys.cpus()[0].brand());
155        }
156        "load_avg" => {
157            let load_avg = System::load_average();
158            println!("one minute     : {}%", load_avg.one);
159            println!("five minutes   : {}%", load_avg.five);
160            println!("fifteen minutes: {}%", load_avg.fifteen);
161        }
162        e if e.starts_with("show ") => {
163            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165            if tmp.len() != 2 {
166                println!("show command takes a pid or a name in parameter!");
167                println!("example: show 1254");
168            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169                match sys.process(pid) {
170                    Some(p) => {
171                        println!("{:?}", *p);
172                        println!(
173                            "Files open/limit: {:?}/{:?}",
174                            p.open_files(),
175                            p.open_files_limit(),
176                        );
177                    }
178                    None => {
179                        println!("pid \"{pid:?}\" not found");
180                    }
181                }
182            } else {
183                let proc_name = tmp[1];
184                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185                    println!("==== {} ====", proc_.name().to_string_lossy());
186                    println!("{proc_:?}");
187                }
188            }
189        }
190        "temperature" => {
191            for component in components.iter() {
192                println!("{component:?}");
193            }
194        }
195        "network" => {
196            for (interface_name, data) in networks.iter() {
197                println!(
198                    "\
199{interface_name}:
200  operational state {}
201  ether {}
202  input data  (new / total): {} / {} B
203  output data (new / total): {} / {} B",
204                    data.operational_state(),
205                    data.mac_address(),
206                    data.received(),
207                    data.total_received(),
208                    data.transmitted(),
209                    data.total_transmitted(),
210                );
211            }
212        }
213        "show" => {
214            println!("'show' command expects a pid number or a process name");
215        }
216        e if e.starts_with("kill ") => {
217            let tmp: Vec<&str> = e
218                .split(' ')
219                .map(|s| s.trim())
220                .filter(|s| !s.is_empty())
221                .collect();
222
223            if tmp.len() != 3 {
224                println!("kill command takes the pid and a signal number in parameter!");
225                println!("example: kill 1254 9");
226            } else {
227                let Ok(pid) = Pid::from_str(tmp[1]) else {
228                    eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
229                    return false;
230                };
231                let Ok(signal) = usize::from_str(tmp[2]) else {
232                    eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
233                    return false;
234                };
235                let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
236                    eprintln!(
237                        "No signal matching {signal}. Use the `signals` command to get the \
238                         list of signals.",
239                    );
240                    return false;
241                };
242
243                match sys.process(pid) {
244                    Some(p) => {
245                        if let Some(res) = p.kill_with(*signal) {
246                            println!("kill: {res}");
247                        } else {
248                            eprintln!("kill: signal not supported on this platform");
249                        }
250                    }
251                    None => {
252                        eprintln!("pid not found");
253                    }
254                }
255            }
256        }
257        "disks" => {
258            for disk in disks {
259                println!("{disk:?}");
260            }
261        }
262        "users" => {
263            for user in users {
264                println!("{:?} => {:?}", user.name(), user.groups());
265            }
266        }
267        "groups" => {
268            for group in Groups::new_with_refreshed_list().list() {
269                println!("{group:?}");
270            }
271        }
272        "boot_time" => {
273            println!("{} seconds", System::boot_time());
274        }
275        "uptime" => {
276            let up = System::uptime();
277            let mut uptime = up;
278            let days = uptime / 86400;
279            uptime -= days * 86400;
280            let hours = uptime / 3600;
281            uptime -= hours * 3600;
282            let minutes = uptime / 60;
283            println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
284        }
285        x if x.starts_with("refresh") => {
286            if x == "refresh" {
287                println!("Getting processes' information...");
288                sys.refresh_all();
289                println!("Done.");
290            } else if x.starts_with("refresh ") {
291                println!("Getting process' information...");
292                if let Some(pid) = x
293                    .split(' ')
294                    .filter_map(|pid| pid.parse().ok())
295                    .take(1)
296                    .next()
297                {
298                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
299                        println!("Process `{pid}` updated successfully");
300                    } else {
301                        println!("Process `{pid}` couldn't be updated...");
302                    }
303                } else {
304                    println!("Invalid [pid] received...");
305                }
306            } else {
307                println!(
308                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
309                     list.",
310                );
311            }
312        }
313        "pid" => {
314            println!(
315                "PID: {}",
316                sysinfo::get_current_pid().expect("failed to get PID")
317            );
318        }
319        "system" => {
320            println!(
321                "System name:              {}\n\
322                 System kernel version:    {}\n\
323                 System OS version:        {}\n\
324                 System OS (long) version: {}\n\
325                 System host name:         {}\n\
326                 System kernel:            {}",
327                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
328                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
329                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
330                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
331                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
332                System::kernel_long_version(),
333            );
334        }
335        "motherboard" => match Motherboard::new() {
336            Some(m) => println!("{m:#?}"),
337            None => println!("No motherboard information available"),
338        },
339        "product" => {
340            println!("{:#?}", Product);
341        }
342        e => {
343            println!(
344                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
345                 list.",
346            );
347        }
348    }
349    false
350}
Source

pub fn vendor_id(&self) -> &str

Returns the CPU’s vendor id.

use sysinfo::{System, RefreshKind, CpuRefreshKind};

let s = System::new_with_specifics(
    RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
);
for cpu in s.cpus() {
    println!("{}", cpu.vendor_id());
}
Examples found in repository?
examples/simple.rs (line 151)
70fn interpret_input(
71    input: &str,
72    sys: &mut System,
73    networks: &mut Networks,
74    disks: &mut Disks,
75    components: &mut Components,
76    users: &mut Users,
77) -> bool {
78    match input.trim() {
79        "help" => print_help(),
80        "refresh_disks" => {
81            println!("Refreshing disk list...");
82            disks.refresh(true);
83            println!("Done.");
84        }
85        "refresh_users" => {
86            println!("Refreshing user list...");
87            users.refresh();
88            println!("Done.");
89        }
90        "refresh_networks" => {
91            println!("Refreshing network list...");
92            networks.refresh(true);
93            println!("Done.");
94        }
95        "refresh_components" => {
96            println!("Refreshing component list...");
97            components.refresh(true);
98            println!("Done.");
99        }
100        "refresh_cpu" => {
101            println!("Refreshing CPUs...");
102            sys.refresh_cpu_all();
103            println!("Done.");
104        }
105        "signals" => {
106            for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107                println!("{:2}:{sig:?}", nb + 1);
108            }
109        }
110        "cpus" => {
111            // Note: you should refresh a few times before using this, so that usage statistics
112            // can be ascertained
113            println!(
114                "number of physical cores: {}",
115                System::physical_core_count()
116                    .map(|c| c.to_string())
117                    .unwrap_or_else(|| "Unknown".to_owned()),
118            );
119            println!("total CPU usage: {}%", sys.global_cpu_usage());
120            for cpu in sys.cpus() {
121                println!("{cpu:?}");
122            }
123        }
124        "memory" => {
125            println!("total memory:     {: >10} KB", sys.total_memory() / 1_000);
126            println!(
127                "available memory: {: >10} KB",
128                sys.available_memory() / 1_000
129            );
130            println!("used memory:      {: >10} KB", sys.used_memory() / 1_000);
131            println!("total swap:       {: >10} KB", sys.total_swap() / 1_000);
132            println!("used swap:        {: >10} KB", sys.used_swap() / 1_000);
133        }
134        "quit" | "exit" => return true,
135        "all" => {
136            for (pid, proc_) in sys.processes() {
137                println!(
138                    "{}:{} status={:?}",
139                    pid,
140                    proc_.name().to_string_lossy(),
141                    proc_.status()
142                );
143            }
144        }
145        "frequency" => {
146            for cpu in sys.cpus() {
147                println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148            }
149        }
150        "vendor_id" => {
151            println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152        }
153        "brand" => {
154            println!("brand: {}", sys.cpus()[0].brand());
155        }
156        "load_avg" => {
157            let load_avg = System::load_average();
158            println!("one minute     : {}%", load_avg.one);
159            println!("five minutes   : {}%", load_avg.five);
160            println!("fifteen minutes: {}%", load_avg.fifteen);
161        }
162        e if e.starts_with("show ") => {
163            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165            if tmp.len() != 2 {
166                println!("show command takes a pid or a name in parameter!");
167                println!("example: show 1254");
168            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169                match sys.process(pid) {
170                    Some(p) => {
171                        println!("{:?}", *p);
172                        println!(
173                            "Files open/limit: {:?}/{:?}",
174                            p.open_files(),
175                            p.open_files_limit(),
176                        );
177                    }
178                    None => {
179                        println!("pid \"{pid:?}\" not found");
180                    }
181                }
182            } else {
183                let proc_name = tmp[1];
184                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185                    println!("==== {} ====", proc_.name().to_string_lossy());
186                    println!("{proc_:?}");
187                }
188            }
189        }
190        "temperature" => {
191            for component in components.iter() {
192                println!("{component:?}");
193            }
194        }
195        "network" => {
196            for (interface_name, data) in networks.iter() {
197                println!(
198                    "\
199{interface_name}:
200  operational state {}
201  ether {}
202  input data  (new / total): {} / {} B
203  output data (new / total): {} / {} B",
204                    data.operational_state(),
205                    data.mac_address(),
206                    data.received(),
207                    data.total_received(),
208                    data.transmitted(),
209                    data.total_transmitted(),
210                );
211            }
212        }
213        "show" => {
214            println!("'show' command expects a pid number or a process name");
215        }
216        e if e.starts_with("kill ") => {
217            let tmp: Vec<&str> = e
218                .split(' ')
219                .map(|s| s.trim())
220                .filter(|s| !s.is_empty())
221                .collect();
222
223            if tmp.len() != 3 {
224                println!("kill command takes the pid and a signal number in parameter!");
225                println!("example: kill 1254 9");
226            } else {
227                let Ok(pid) = Pid::from_str(tmp[1]) else {
228                    eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
229                    return false;
230                };
231                let Ok(signal) = usize::from_str(tmp[2]) else {
232                    eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
233                    return false;
234                };
235                let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
236                    eprintln!(
237                        "No signal matching {signal}. Use the `signals` command to get the \
238                         list of signals.",
239                    );
240                    return false;
241                };
242
243                match sys.process(pid) {
244                    Some(p) => {
245                        if let Some(res) = p.kill_with(*signal) {
246                            println!("kill: {res}");
247                        } else {
248                            eprintln!("kill: signal not supported on this platform");
249                        }
250                    }
251                    None => {
252                        eprintln!("pid not found");
253                    }
254                }
255            }
256        }
257        "disks" => {
258            for disk in disks {
259                println!("{disk:?}");
260            }
261        }
262        "users" => {
263            for user in users {
264                println!("{:?} => {:?}", user.name(), user.groups());
265            }
266        }
267        "groups" => {
268            for group in Groups::new_with_refreshed_list().list() {
269                println!("{group:?}");
270            }
271        }
272        "boot_time" => {
273            println!("{} seconds", System::boot_time());
274        }
275        "uptime" => {
276            let up = System::uptime();
277            let mut uptime = up;
278            let days = uptime / 86400;
279            uptime -= days * 86400;
280            let hours = uptime / 3600;
281            uptime -= hours * 3600;
282            let minutes = uptime / 60;
283            println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
284        }
285        x if x.starts_with("refresh") => {
286            if x == "refresh" {
287                println!("Getting processes' information...");
288                sys.refresh_all();
289                println!("Done.");
290            } else if x.starts_with("refresh ") {
291                println!("Getting process' information...");
292                if let Some(pid) = x
293                    .split(' ')
294                    .filter_map(|pid| pid.parse().ok())
295                    .take(1)
296                    .next()
297                {
298                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
299                        println!("Process `{pid}` updated successfully");
300                    } else {
301                        println!("Process `{pid}` couldn't be updated...");
302                    }
303                } else {
304                    println!("Invalid [pid] received...");
305                }
306            } else {
307                println!(
308                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
309                     list.",
310                );
311            }
312        }
313        "pid" => {
314            println!(
315                "PID: {}",
316                sysinfo::get_current_pid().expect("failed to get PID")
317            );
318        }
319        "system" => {
320            println!(
321                "System name:              {}\n\
322                 System kernel version:    {}\n\
323                 System OS version:        {}\n\
324                 System OS (long) version: {}\n\
325                 System host name:         {}\n\
326                 System kernel:            {}",
327                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
328                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
329                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
330                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
331                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
332                System::kernel_long_version(),
333            );
334        }
335        "motherboard" => match Motherboard::new() {
336            Some(m) => println!("{m:#?}"),
337            None => println!("No motherboard information available"),
338        },
339        "product" => {
340            println!("{:#?}", Product);
341        }
342        e => {
343            println!(
344                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
345                 list.",
346            );
347        }
348    }
349    false
350}
Source

pub fn brand(&self) -> &str

Returns the CPU’s brand.

use sysinfo::{System, RefreshKind, CpuRefreshKind};

let s = System::new_with_specifics(
    RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
);
for cpu in s.cpus() {
    println!("{}", cpu.brand());
}
Examples found in repository?
examples/simple.rs (line 154)
70fn interpret_input(
71    input: &str,
72    sys: &mut System,
73    networks: &mut Networks,
74    disks: &mut Disks,
75    components: &mut Components,
76    users: &mut Users,
77) -> bool {
78    match input.trim() {
79        "help" => print_help(),
80        "refresh_disks" => {
81            println!("Refreshing disk list...");
82            disks.refresh(true);
83            println!("Done.");
84        }
85        "refresh_users" => {
86            println!("Refreshing user list...");
87            users.refresh();
88            println!("Done.");
89        }
90        "refresh_networks" => {
91            println!("Refreshing network list...");
92            networks.refresh(true);
93            println!("Done.");
94        }
95        "refresh_components" => {
96            println!("Refreshing component list...");
97            components.refresh(true);
98            println!("Done.");
99        }
100        "refresh_cpu" => {
101            println!("Refreshing CPUs...");
102            sys.refresh_cpu_all();
103            println!("Done.");
104        }
105        "signals" => {
106            for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107                println!("{:2}:{sig:?}", nb + 1);
108            }
109        }
110        "cpus" => {
111            // Note: you should refresh a few times before using this, so that usage statistics
112            // can be ascertained
113            println!(
114                "number of physical cores: {}",
115                System::physical_core_count()
116                    .map(|c| c.to_string())
117                    .unwrap_or_else(|| "Unknown".to_owned()),
118            );
119            println!("total CPU usage: {}%", sys.global_cpu_usage());
120            for cpu in sys.cpus() {
121                println!("{cpu:?}");
122            }
123        }
124        "memory" => {
125            println!("total memory:     {: >10} KB", sys.total_memory() / 1_000);
126            println!(
127                "available memory: {: >10} KB",
128                sys.available_memory() / 1_000
129            );
130            println!("used memory:      {: >10} KB", sys.used_memory() / 1_000);
131            println!("total swap:       {: >10} KB", sys.total_swap() / 1_000);
132            println!("used swap:        {: >10} KB", sys.used_swap() / 1_000);
133        }
134        "quit" | "exit" => return true,
135        "all" => {
136            for (pid, proc_) in sys.processes() {
137                println!(
138                    "{}:{} status={:?}",
139                    pid,
140                    proc_.name().to_string_lossy(),
141                    proc_.status()
142                );
143            }
144        }
145        "frequency" => {
146            for cpu in sys.cpus() {
147                println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148            }
149        }
150        "vendor_id" => {
151            println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152        }
153        "brand" => {
154            println!("brand: {}", sys.cpus()[0].brand());
155        }
156        "load_avg" => {
157            let load_avg = System::load_average();
158            println!("one minute     : {}%", load_avg.one);
159            println!("five minutes   : {}%", load_avg.five);
160            println!("fifteen minutes: {}%", load_avg.fifteen);
161        }
162        e if e.starts_with("show ") => {
163            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165            if tmp.len() != 2 {
166                println!("show command takes a pid or a name in parameter!");
167                println!("example: show 1254");
168            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169                match sys.process(pid) {
170                    Some(p) => {
171                        println!("{:?}", *p);
172                        println!(
173                            "Files open/limit: {:?}/{:?}",
174                            p.open_files(),
175                            p.open_files_limit(),
176                        );
177                    }
178                    None => {
179                        println!("pid \"{pid:?}\" not found");
180                    }
181                }
182            } else {
183                let proc_name = tmp[1];
184                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185                    println!("==== {} ====", proc_.name().to_string_lossy());
186                    println!("{proc_:?}");
187                }
188            }
189        }
190        "temperature" => {
191            for component in components.iter() {
192                println!("{component:?}");
193            }
194        }
195        "network" => {
196            for (interface_name, data) in networks.iter() {
197                println!(
198                    "\
199{interface_name}:
200  operational state {}
201  ether {}
202  input data  (new / total): {} / {} B
203  output data (new / total): {} / {} B",
204                    data.operational_state(),
205                    data.mac_address(),
206                    data.received(),
207                    data.total_received(),
208                    data.transmitted(),
209                    data.total_transmitted(),
210                );
211            }
212        }
213        "show" => {
214            println!("'show' command expects a pid number or a process name");
215        }
216        e if e.starts_with("kill ") => {
217            let tmp: Vec<&str> = e
218                .split(' ')
219                .map(|s| s.trim())
220                .filter(|s| !s.is_empty())
221                .collect();
222
223            if tmp.len() != 3 {
224                println!("kill command takes the pid and a signal number in parameter!");
225                println!("example: kill 1254 9");
226            } else {
227                let Ok(pid) = Pid::from_str(tmp[1]) else {
228                    eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
229                    return false;
230                };
231                let Ok(signal) = usize::from_str(tmp[2]) else {
232                    eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
233                    return false;
234                };
235                let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
236                    eprintln!(
237                        "No signal matching {signal}. Use the `signals` command to get the \
238                         list of signals.",
239                    );
240                    return false;
241                };
242
243                match sys.process(pid) {
244                    Some(p) => {
245                        if let Some(res) = p.kill_with(*signal) {
246                            println!("kill: {res}");
247                        } else {
248                            eprintln!("kill: signal not supported on this platform");
249                        }
250                    }
251                    None => {
252                        eprintln!("pid not found");
253                    }
254                }
255            }
256        }
257        "disks" => {
258            for disk in disks {
259                println!("{disk:?}");
260            }
261        }
262        "users" => {
263            for user in users {
264                println!("{:?} => {:?}", user.name(), user.groups());
265            }
266        }
267        "groups" => {
268            for group in Groups::new_with_refreshed_list().list() {
269                println!("{group:?}");
270            }
271        }
272        "boot_time" => {
273            println!("{} seconds", System::boot_time());
274        }
275        "uptime" => {
276            let up = System::uptime();
277            let mut uptime = up;
278            let days = uptime / 86400;
279            uptime -= days * 86400;
280            let hours = uptime / 3600;
281            uptime -= hours * 3600;
282            let minutes = uptime / 60;
283            println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
284        }
285        x if x.starts_with("refresh") => {
286            if x == "refresh" {
287                println!("Getting processes' information...");
288                sys.refresh_all();
289                println!("Done.");
290            } else if x.starts_with("refresh ") {
291                println!("Getting process' information...");
292                if let Some(pid) = x
293                    .split(' ')
294                    .filter_map(|pid| pid.parse().ok())
295                    .take(1)
296                    .next()
297                {
298                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
299                        println!("Process `{pid}` updated successfully");
300                    } else {
301                        println!("Process `{pid}` couldn't be updated...");
302                    }
303                } else {
304                    println!("Invalid [pid] received...");
305                }
306            } else {
307                println!(
308                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
309                     list.",
310                );
311            }
312        }
313        "pid" => {
314            println!(
315                "PID: {}",
316                sysinfo::get_current_pid().expect("failed to get PID")
317            );
318        }
319        "system" => {
320            println!(
321                "System name:              {}\n\
322                 System kernel version:    {}\n\
323                 System OS version:        {}\n\
324                 System OS (long) version: {}\n\
325                 System host name:         {}\n\
326                 System kernel:            {}",
327                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
328                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
329                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
330                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
331                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
332                System::kernel_long_version(),
333            );
334        }
335        "motherboard" => match Motherboard::new() {
336            Some(m) => println!("{m:#?}"),
337            None => println!("No motherboard information available"),
338        },
339        "product" => {
340            println!("{:#?}", Product);
341        }
342        e => {
343            println!(
344                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
345                 list.",
346            );
347        }
348    }
349    false
350}
Source

pub fn frequency(&self) -> u64

Returns the CPU’s frequency (in MHz).

use sysinfo::{System, RefreshKind, CpuRefreshKind};

let s = System::new_with_specifics(
    RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
);
for cpu in s.cpus() {
    println!("{}", cpu.frequency());
}
Examples found in repository?
examples/simple.rs (line 147)
70fn interpret_input(
71    input: &str,
72    sys: &mut System,
73    networks: &mut Networks,
74    disks: &mut Disks,
75    components: &mut Components,
76    users: &mut Users,
77) -> bool {
78    match input.trim() {
79        "help" => print_help(),
80        "refresh_disks" => {
81            println!("Refreshing disk list...");
82            disks.refresh(true);
83            println!("Done.");
84        }
85        "refresh_users" => {
86            println!("Refreshing user list...");
87            users.refresh();
88            println!("Done.");
89        }
90        "refresh_networks" => {
91            println!("Refreshing network list...");
92            networks.refresh(true);
93            println!("Done.");
94        }
95        "refresh_components" => {
96            println!("Refreshing component list...");
97            components.refresh(true);
98            println!("Done.");
99        }
100        "refresh_cpu" => {
101            println!("Refreshing CPUs...");
102            sys.refresh_cpu_all();
103            println!("Done.");
104        }
105        "signals" => {
106            for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107                println!("{:2}:{sig:?}", nb + 1);
108            }
109        }
110        "cpus" => {
111            // Note: you should refresh a few times before using this, so that usage statistics
112            // can be ascertained
113            println!(
114                "number of physical cores: {}",
115                System::physical_core_count()
116                    .map(|c| c.to_string())
117                    .unwrap_or_else(|| "Unknown".to_owned()),
118            );
119            println!("total CPU usage: {}%", sys.global_cpu_usage());
120            for cpu in sys.cpus() {
121                println!("{cpu:?}");
122            }
123        }
124        "memory" => {
125            println!("total memory:     {: >10} KB", sys.total_memory() / 1_000);
126            println!(
127                "available memory: {: >10} KB",
128                sys.available_memory() / 1_000
129            );
130            println!("used memory:      {: >10} KB", sys.used_memory() / 1_000);
131            println!("total swap:       {: >10} KB", sys.total_swap() / 1_000);
132            println!("used swap:        {: >10} KB", sys.used_swap() / 1_000);
133        }
134        "quit" | "exit" => return true,
135        "all" => {
136            for (pid, proc_) in sys.processes() {
137                println!(
138                    "{}:{} status={:?}",
139                    pid,
140                    proc_.name().to_string_lossy(),
141                    proc_.status()
142                );
143            }
144        }
145        "frequency" => {
146            for cpu in sys.cpus() {
147                println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148            }
149        }
150        "vendor_id" => {
151            println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152        }
153        "brand" => {
154            println!("brand: {}", sys.cpus()[0].brand());
155        }
156        "load_avg" => {
157            let load_avg = System::load_average();
158            println!("one minute     : {}%", load_avg.one);
159            println!("five minutes   : {}%", load_avg.five);
160            println!("fifteen minutes: {}%", load_avg.fifteen);
161        }
162        e if e.starts_with("show ") => {
163            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165            if tmp.len() != 2 {
166                println!("show command takes a pid or a name in parameter!");
167                println!("example: show 1254");
168            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169                match sys.process(pid) {
170                    Some(p) => {
171                        println!("{:?}", *p);
172                        println!(
173                            "Files open/limit: {:?}/{:?}",
174                            p.open_files(),
175                            p.open_files_limit(),
176                        );
177                    }
178                    None => {
179                        println!("pid \"{pid:?}\" not found");
180                    }
181                }
182            } else {
183                let proc_name = tmp[1];
184                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185                    println!("==== {} ====", proc_.name().to_string_lossy());
186                    println!("{proc_:?}");
187                }
188            }
189        }
190        "temperature" => {
191            for component in components.iter() {
192                println!("{component:?}");
193            }
194        }
195        "network" => {
196            for (interface_name, data) in networks.iter() {
197                println!(
198                    "\
199{interface_name}:
200  operational state {}
201  ether {}
202  input data  (new / total): {} / {} B
203  output data (new / total): {} / {} B",
204                    data.operational_state(),
205                    data.mac_address(),
206                    data.received(),
207                    data.total_received(),
208                    data.transmitted(),
209                    data.total_transmitted(),
210                );
211            }
212        }
213        "show" => {
214            println!("'show' command expects a pid number or a process name");
215        }
216        e if e.starts_with("kill ") => {
217            let tmp: Vec<&str> = e
218                .split(' ')
219                .map(|s| s.trim())
220                .filter(|s| !s.is_empty())
221                .collect();
222
223            if tmp.len() != 3 {
224                println!("kill command takes the pid and a signal number in parameter!");
225                println!("example: kill 1254 9");
226            } else {
227                let Ok(pid) = Pid::from_str(tmp[1]) else {
228                    eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
229                    return false;
230                };
231                let Ok(signal) = usize::from_str(tmp[2]) else {
232                    eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
233                    return false;
234                };
235                let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
236                    eprintln!(
237                        "No signal matching {signal}. Use the `signals` command to get the \
238                         list of signals.",
239                    );
240                    return false;
241                };
242
243                match sys.process(pid) {
244                    Some(p) => {
245                        if let Some(res) = p.kill_with(*signal) {
246                            println!("kill: {res}");
247                        } else {
248                            eprintln!("kill: signal not supported on this platform");
249                        }
250                    }
251                    None => {
252                        eprintln!("pid not found");
253                    }
254                }
255            }
256        }
257        "disks" => {
258            for disk in disks {
259                println!("{disk:?}");
260            }
261        }
262        "users" => {
263            for user in users {
264                println!("{:?} => {:?}", user.name(), user.groups());
265            }
266        }
267        "groups" => {
268            for group in Groups::new_with_refreshed_list().list() {
269                println!("{group:?}");
270            }
271        }
272        "boot_time" => {
273            println!("{} seconds", System::boot_time());
274        }
275        "uptime" => {
276            let up = System::uptime();
277            let mut uptime = up;
278            let days = uptime / 86400;
279            uptime -= days * 86400;
280            let hours = uptime / 3600;
281            uptime -= hours * 3600;
282            let minutes = uptime / 60;
283            println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
284        }
285        x if x.starts_with("refresh") => {
286            if x == "refresh" {
287                println!("Getting processes' information...");
288                sys.refresh_all();
289                println!("Done.");
290            } else if x.starts_with("refresh ") {
291                println!("Getting process' information...");
292                if let Some(pid) = x
293                    .split(' ')
294                    .filter_map(|pid| pid.parse().ok())
295                    .take(1)
296                    .next()
297                {
298                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
299                        println!("Process `{pid}` updated successfully");
300                    } else {
301                        println!("Process `{pid}` couldn't be updated...");
302                    }
303                } else {
304                    println!("Invalid [pid] received...");
305                }
306            } else {
307                println!(
308                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
309                     list.",
310                );
311            }
312        }
313        "pid" => {
314            println!(
315                "PID: {}",
316                sysinfo::get_current_pid().expect("failed to get PID")
317            );
318        }
319        "system" => {
320            println!(
321                "System name:              {}\n\
322                 System kernel version:    {}\n\
323                 System OS version:        {}\n\
324                 System OS (long) version: {}\n\
325                 System host name:         {}\n\
326                 System kernel:            {}",
327                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
328                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
329                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
330                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
331                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
332                System::kernel_long_version(),
333            );
334        }
335        "motherboard" => match Motherboard::new() {
336            Some(m) => println!("{m:#?}"),
337            None => println!("No motherboard information available"),
338        },
339        "product" => {
340            println!("{:#?}", Product);
341        }
342        e => {
343            println!(
344                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
345                 list.",
346            );
347        }
348    }
349    false
350}

Trait Implementations§

Source§

impl Debug for Cpu

Available on crate feature system only.
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Serialize for Cpu

Available on crate feature system only.
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for Cpu

§

impl RefUnwindSafe for Cpu

§

impl Send for Cpu

§

impl Sync for Cpu

§

impl Unpin for Cpu

§

impl UnsafeUnpin for Cpu

§

impl UnwindSafe for Cpu

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.