Rust stdout Is Line-Buffered: println! vs BufWriter, Measured
println! makes one write(2) per line, even into a file or a pipe. On an M2 Pro, BufWriter wrote 8.7x faster to a file; eprintln! was 114x slower.
A Rust CLI that prints a million lines with println! is slow, and most people assume the cause is formatting or the lock that println! takes on every call. Neither is the cause. Rust’s stdout is a LineWriter, so each newline triggers a write(2) system call. That happens on a file and on a pipe as well as on a terminal. C’s printf behaves differently: it buffers fully as soon as its output is not a terminal.
I measured this with one small crate in this blog’s repository, scripts/rust-buffered-io/. It is about 300 lines of Rust plus two short C files, uses only the standard library and builds with cargo build --offline. It writes the same LLM-gateway access log in eight ways and sends it to three places: a file, a pipe and a terminal. It also reads the log back in six ways.
The short version, 1,000,000 lines of about 70 bytes, median of 5 interleaved runs:
| How the line is written | to a file | to a pipe | to a terminal | write(2) calls |
|---|---|---|---|---|
println!(...) | 2,026 ns | 732 ns | 1,648 ns | 1,000,000 |
io::stdout().lock() + writeln! | 2,155 ns | 742 ns | 1,532 ns | 1,000,000 |
eprintln!(...) | 26,493 ns | 5,659 ns | 17,560 ns | 14,110,590 |
BufWriter::new(stdout().lock()) | 233 ns | 167 ns | 527 ns | 16,743 |
BufWriter with 64 KiB | 227 ns | 144 ns | 474 ns | 2,101 |
BufWriter + format!() per line | 237 ns | 189 ns | 532 ns | 8,811 |
BufWriter on raw fd 1 (skips the LineWriter) | 200 ns | 164 ns | 491 ns | 8,615 |
C printf (reference) | 354 ns | 302 ns | 1,644 ns | n/a |
The things worth knowing:
- Taking the lock yourself does nothing.
stdout().lock()withwriteln!costs the same asprintln!(2,155 vs 2,026 ns per line to a file). The cost is the system call, not the mutex. BufWritermakes writing to a file 8.7x faster, to a pipe 4.4x and to a terminal 3.1x. The file run retires 11.5x fewer instructions (2.59 G instead of 29.78 G) and spends 0.06 s in the kernel instead of 1.68 s.eprintln!is the slowest way to log. stderr has no buffer at all, so one line becomes about 14write(2)calls, one per formatted piece. It is 114x slower thanBufWriterto a file.- Wrapping stdout in a
BufWriterstill splits writes. TheLineWriterunder it holds back each partial line, so you get twice as many calls as you would expect (16,743 instead of about 8,600). std::process::exitloses the tail. ABufWriterthat is never dropped never flushes. In our run the last 6 lines and 363 bytes never reached the file, and the last line stopped in the middle of a number.
The program under test
iobench write <variant> <lines> prints one access-log line per simulated request. Each line is derived from its line number with a seeded hash, so every variant prints byte-identical output. measure.sh checks that with cmp before it times anything, including the C reference:
1
2
req=0000000 model=llama-3.1-8b tokens_in=717 tokens_out=772 ms=819.496
req=0000001 model=smollm3-3b tokens_in=1244 tokens_out=754 ms=1505.325
Each line has one integer field padded to seven digits, two more integers, a string and a float with three decimals. That is a realistic mix for logs and CSV-like output. The variants differ only in the lines that do the writing:
1
2
3
4
5
6
7
// println: one LineWriter flush, so one write(2), per line
println!("req={:07} model={} tokens_in={} tokens_out={} ms={:.3}", r.id, r.model, r.tokens_in, r.tokens_out, r.ms);
// bufwriter: 8 KiB buffer in front of the locked stdout, flushed once at the end
let mut out = BufWriter::new(io::stdout().lock());
writeln!(out, "req={:07} model={} tokens_in={} tokens_out={} ms={:.3}", r.id, r.model, r.tokens_in, r.tokens_out, r.ms)?;
out.flush()?;
Test machine: Apple M2 Pro, macOS 27.0.1, rustc 1.95.0, --release. The Mac was shared with other jobs (load average 4.8 to 7.6 during the runs), so every cell is the median of 5 runs. The runs are interleaved: run 1 of every cell, then run 2 of every cell, and so on, so drift in host load affects all cells alike.
How we counted the system calls
Wall time tells you that something is slow. A system-call count tells you why. On macOS, strace does not exist and dtruss needs root and SIP turned off. We used syscount.c.txt instead: a 50-line C file built as a .dylib. It interposes write, writev and read through DYLD_INSERT_LIBRARIES, counts the calls and their bytes, and appends one line to a file at exit. This works on our own unsigned binaries without root. It does not work on system binaries such as /bin/cat, which SIP protects.
The counts are the same for all three sinks (the full table is in scripts/data/rust-buffered-io-m2pro.json). Rust’s choice of buffering does not depend on what stdout is connected to. The standard library docs for std::io::stdout describe the handle as line-buffered “when connected to a terminal”. The measurement shows the same one-write-per-line behaviour for a file and a pipe too.
C stdio is the reference here. cprintf.c.txt prints the same bytes with printf. It costs 354 ns per line to a file, then 1,644 ns to a terminal, where libc switches to line buffering. To a terminal, C and println! are about equally slow. To a file, C is 5.7x faster than println! because libc buffers and Rust does not. We could not count printf’s system calls, because libc calls its own internal write and interposition does not see that. The timing and the kernel time (1.25 s to a terminal, 0.06 s to a file) show the same switch.
Where println! spends its time
A CPU profile of each version writing into a pipe, taken with /usr/bin/sample (4 s at 1 ms, no root needed) and drawn with the flame-graph scripts from our Rust profiling guide:
With println!, 89.7% of the samples are inside the write system call and 9.9% are formatting. With BufWriter, formatting rises to 73.8% and write falls to 24.7%. The total time per line dropped 4.4x, so the formatting did not get slower. It is the same work, and it is now the biggest share of a much smaller total. The next optimisation for this program would be the float formatting (the ms={:.3} field), not the I/O.
Four details that change the numbers
The double write under BufWriter<StdoutLock>. Wrapping the locked stdout in a BufWriter does not remove the LineWriter. It only puts a second buffer in front of it. writeln! writes each formatted piece separately ("req=", the number, " model=", and so on), so the BufWriter fills up partway through a line. It then passes 8 KiB to the LineWriter, which writes up to the last newline and keeps the partial line. That partial line goes out as its own tiny write just before the next big one. Here are the first sizes the counter logged:
1
2
3
bufwriter 8186,6,8129,63,8146,40,8133,57,8157,28,8172,18,8179,11,8127,63
bufwriter_fd1 8192,8192,8186,8190,8185,8190,8190,8190,8188,8187,8187,8192,8190,8182,8192,8192
bufwriter_format 8186,8135,8141,8168,8146,8125,8129,8131,8182,8145,8157,8190,8129,8167,8136,8127
The bufwriter_fd1 variant wraps a File built from file descriptor 1 (in a ManuallyDrop, so it never closes stdout) and skips the LineWriter. It makes 8,615 calls instead of 16,743. The time per line drops from 233 to 200 ns to a file, but the run ranges overlap (177 to 250 ns against 204 to 270 ns). That is a real halving of system calls and a small saving in time. Most programs should keep the simple BufWriter::new(stdout().lock()).
format! per line is cheaper than it looks. The bufwriter_format variant allocates a new String for every line: 1,000,003 heap allocations in total, against 3 for plain BufWriter. That adds 2% to a file and 13% to a pipe. Because each line reaches the BufWriter in one piece, its buffer always flushes on a line boundary, so it also avoids the double write above (8,811 calls). Avoid the allocation in a hot loop, but it is not the main cost.
A bigger buffer helps a little. 64 KiB instead of 8 KiB cut the call count from 16,743 to 2,101 and saved 3 to 14% per line. The default is fine. Raise the capacity only if the output is large and every percent counts.
A terminal is slow anyway. Even buffered, writing to the terminal cost 527 ns per line against 233 ns to a file, and the extra time is kernel time in the pseudo-terminal driver (0.21 s of system time against 0.06 s). If people watch a program’s output scroll by, the terminal is the bottleneck whatever you do. Write the bulk output to a file and print a summary.
The bug: exit() skips Drop
std::process::exit ends the process without running destructors. A BufWriter flushes in its Drop, so whatever is still in its buffer is lost. It does not panic and it does not report an error:
How much you lose depends only on where the last flush fell. measure.sh repeats the same exit at ten output sizes from 100,000 to 1,000,000 lines. Every run lost data, from 6 lines (363 bytes) to 109 lines (7,707 bytes). In nine of the ten runs the file also ended in the middle of a line. The usual way this happens is a CLI that calls exit(code) after printing its results, or a main that returns through a helper which calls exit. A test that checks the first lines of the output will not catch it. Call out.flush()? before any exit(), or return an ExitCode from main so that destructors run.
Reading: lines() allocates, bytes() without BufReader crawls
The read side has its own version of the same problem. The input is the same log, 1,000,000 lines and 70.5 MB, read from stdin. Each variant adds up the tokens_out field and prints the same checksum (450,200,074):
.lines()costs one allocation per line (1,008,491 in total) and is the slowest of the line-based readers at 117.1 ns per line. Reusing one buffer withread_linemakes it 78.9 ns.read_until(b'\n')into aVec<u8>also skips the UTF-8 check and takes 69.6 ns. That is 1.7x faster for a two-line change.read_to_stringis as fast asread_until, 71.6 ns, with 24readcalls instead of 8,612. It holds the whole file in memory, though: its peak footprint was 74.1 MB against 1.3 MB for the streaming readers. That is fine for config files and a bad idea for logs.File::bytes()without aBufReadermakes oneread(2)per byte. We counted 1,410,414 calls for 1,410,413 bytes, plus one call that returned EOF. That is 37,672 ns per line, 160x slower than the same loop over aBufReader. It ran only on the first 20,000 lines, because the full file would take 70.5 million system calls. Clippy has a lint for this case,unbuffered_bytes. Turn it on if your code reads files byte by byte.
The read timings are noisier than the write timings. A preliminary run of the same binary an hour earlier, at a lower host load, measured .lines() at 81 ns and read_until at 50 ns. The ratios between the variants were about the same in both runs.
Reproduce it
1
2
3
4
bash scripts/rust-buffered-io/measure.sh /tmp/iobench # about 9 minutes on a loaded M2 Pro
bash scripts/rust-buffered-io/profile.sh /tmp/iobench # two 4 s CPU profiles into a pipe
python3 scripts/rust-buffered-io/summarise.py /tmp/iobench # writes scripts/data/rust-buffered-io-m2pro.json
python3 scripts/rust-buffered-io/gen_images.py /tmp/iobench # the charts and panels in this post
gen_images.py expects the two flame-graph SVGs as PNG screenshots in /tmp/iobench/shots/. We took them with headless Chromium. The terminal panels print the captured files as they are, and the charts are drawn from the JSON.
What this does not cover: Linux and Windows (Linux pipes and terminals have different costs, but the LineWriter around stdout is the same code), tracing or log subscribers (each brings its own buffering), and async writers. The ratios should carry over. The absolute nanoseconds will not.
The checklist
- A program that prints more than a few hundred lines writes through
let mut out = BufWriter::new(io::stdout().lock());and callsout.flush()?at the end. That is two lines of code, and the output gets 3x to 9x faster depending on where it goes. - Locking stdout yourself without a
BufWriteris not an optimisation. eprintln!in a loop is the slowest way to log in Rust. It is fine for errors, not for progress output or log streams.- Never call
std::process::exitwhile aBufWriteris alive. Flush first, or return anExitCode. - Read lines with
read_lineorread_untilinto a reused buffer, not.lines(). Never call.bytes()on an unbufferedFile. - Measure with a system-call count before you tune anything else. One
write(2)per line was 90% ofprintln!’s time here.
Hive, Lamplit Labs’ open-source, self-improving (RSI) agent harness at hivefleet.dev, writes and checks this blog as part of an AI-native SDLC. Agents propose a change, measure it against a baseline and keep only what the numbers support. This post went through the same loop: every number above comes from a script in the repository that a reviewer can rerun, and the build checks every image for alt text and every header for the right aspect ratio.
Related reading
- Rust Profiling Practical Guide: sample, Flame Graphs and a Counting Allocator, Measured: the profiling scripts used for the flame graphs above.
- Profiling a Rust LLM Token Batcher with cargo flamegraph: Cutting Allocations 74%: the allocation side of the same kind of hot loop.
- Rust Release Profiles in Production: LTO, codegen-units, and target-cpu: compiler settings, which matter less than a missing
BufWriter. - Rust vs Go for a CLI Tool: Startup, Binary Size, Build Time and the Day-Two Costs: the kind of program where this matters most.
- Hive: Lamplit Labs’ open-source, self-improving (RSI) agent harness: the product mentioned above.





