Skip to content

Commit db8ecf5

Browse files
committed
top: optimize
1 parent d29e05a commit db8ecf5

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

src/uu/top/src/header.rs

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,6 @@ extern "C" {
3535
) -> libc::c_int;
3636
}
3737

38-
#[cfg(target_os = "macos")]
39-
fn todo() -> String {
40-
"TODO".into()
41-
}
42-
4338
fn format_memory(memory_b: u64, unit: u64) -> f64 {
4439
ByteSize::b(memory_b).0 as f64 / unit as f64
4540
}
@@ -55,6 +50,7 @@ pub fn get_nusers_systemd() -> uucore::error::UResult<usize> {
5550
use uucore::error::USimpleError;
5651
use uucore::libc::*;
5752

53+
// SAFETY: sd_booted to check if system is booted with systemd.
5854
unsafe {
5955
// systemd
6056
if sd_booted() > 0 {
@@ -210,25 +206,28 @@ fn cpu() -> String {
210206
interrupt_time: 0,
211207
interrupt_count: 0,
212208
};
209+
// SAFETY: malloc is safe to use here. We free the memory after we are done with it. If action fails, all "time" will be 0.
213210
unsafe {
214211
let len = n_cpu * size_of::<SystemProcessorPerformanceInformation>();
215212
let data = malloc(len);
216-
let _ = NtQuerySystemInformation(
213+
let status = NtQuerySystemInformation(
217214
windows_sys::Wdk::System::SystemInformation::SystemProcessorPerformanceInformation,
218215
data,
219216
(n_cpu * size_of::<SystemProcessorPerformanceInformation>()) as u32,
220217
std::ptr::null_mut(),
221218
);
222-
for i in 0..n_cpu {
223-
let cpu = data.add(i * size_of::<SystemProcessorPerformanceInformation>())
224-
as *const SystemProcessorPerformanceInformation;
225-
let cpu = cpu.as_ref().unwrap();
226-
cpu_load.idle_time += cpu.idle_time;
227-
cpu_load.kernel_time += cpu.kernel_time;
228-
cpu_load.user_time += cpu.user_time;
229-
cpu_load.dpc_time += cpu.dpc_time;
230-
cpu_load.interrupt_time += cpu.interrupt_time;
231-
cpu_load.interrupt_count += cpu.interrupt_count;
219+
if status == 0 {
220+
for i in 0..n_cpu {
221+
let cpu = data.add(i * size_of::<SystemProcessorPerformanceInformation>())
222+
as *const SystemProcessorPerformanceInformation;
223+
let cpu = cpu.as_ref().unwrap();
224+
cpu_load.idle_time += cpu.idle_time;
225+
cpu_load.kernel_time += cpu.kernel_time;
226+
cpu_load.user_time += cpu.user_time;
227+
cpu_load.dpc_time += cpu.dpc_time;
228+
cpu_load.interrupt_time += cpu.interrupt_time;
229+
cpu_load.interrupt_count += cpu.interrupt_count;
230+
}
232231
}
233232
}
234233
let total = cpu_load.idle_time
@@ -249,7 +248,7 @@ fn cpu() -> String {
249248
//TODO: Implement for macos
250249
#[cfg(target_os = "macos")]
251250
fn cpu() -> String {
252-
todo()
251+
"TODO".into()
253252
}
254253

255254
fn memory(scale_summary_mem: Option<&String>) -> String {

0 commit comments

Comments
 (0)