Skip to content

Commit 9da87b9

Browse files
committed
perf: use stack buffer and direct write syscall in print_system_info
Eliminates ~1KB stdout buffering allocation by using Cursor<&mut [u8]> and libc::write instead of format!() + stdout().write_all()
1 parent 8376e9d commit 9da87b9

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

src/main.rs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ mod syscall;
55
mod system;
66
mod uptime;
77

8-
use std::io::{Write, stdout};
8+
use std::io::{self, Cursor, Write};
99

1010
pub use microfetch_lib::UtsName;
1111

@@ -81,7 +81,13 @@ fn print_system_info(
8181
let cyan = COLORS.cyan;
8282
let blue = COLORS.blue;
8383
let reset = COLORS.reset;
84-
let system_info = format!("
84+
85+
let mut buf = [0u8; 2048];
86+
let mut cursor = Cursor::new(&mut buf[..]);
87+
88+
write!(
89+
cursor,
90+
"
8591
{cyan} ▟█▖ {blue}▝█▙ ▗█▛ {user_info} ~{reset}
8692
{cyan} ▗▄▄▟██▄▄▄▄▄{blue}▝█▙█▛ {cyan}▖ {cyan} {blue}System{reset}  {os_name}
8793
{cyan} ▀▀▀▀▀▀▀▀▀▀▀▘{blue}▝██ {cyan}▟█▖ {cyan} {blue}Kernel{reset}  {kernel_version}
@@ -90,7 +96,16 @@ fn print_system_info(
9096
{blue} ▟█▛{cyan}▗█▖ {cyan}▟█▛ {cyan} {blue}Desktop{reset}  {desktop}
9197
{blue} ▝█▛ {cyan}██▖{blue}▗▄▄▄▄▄▄▄▄▄▄▄ {cyan} {blue}Memory{reset}  {memory_usage}
9298
{blue} ▝ {cyan}▟█▜█▖{blue}▀▀▀▀▀██▛▀▀▘ {cyan}󱥎 {blue}Storage (/){reset}  {storage}
93-
{cyan} ▟█▘ ▜█▖ {blue}▝█▛ {cyan} {blue}Colors{reset}  {colors}\n");
99+
{cyan} ▟█▘ ▜█▖ {blue}▝█▛ {cyan} {blue}Colors{reset}  {colors}\n"
100+
)?;
101+
102+
#[allow(clippy::cast_possible_truncation)]
103+
let len = cursor.position() as usize;
94104

95-
Ok(stdout().write_all(system_info.as_bytes())?)
105+
// Direct syscall to avoid stdout buffering allocation
106+
let written = unsafe { libc::write(libc::STDOUT_FILENO, buf.as_ptr().cast(), len) };
107+
if written < 0 {
108+
return Err(io::Error::last_os_error().into());
109+
}
110+
Ok(())
96111
}

0 commit comments

Comments
 (0)