Post

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.

Rust stdout Is Line-Buffered: println! vs BufWriter, Measured

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 writtento a fileto a pipeto a terminalwrite(2) calls
println!(...)2,026 ns732 ns1,648 ns1,000,000
io::stdout().lock() + writeln!2,155 ns742 ns1,532 ns1,000,000
eprintln!(...)26,493 ns5,659 ns17,560 ns14,110,590
BufWriter::new(stdout().lock())233 ns167 ns527 ns16,743
BufWriter with 64 KiB227 ns144 ns474 ns2,101
BufWriter + format!() per line237 ns189 ns532 ns8,811
BufWriter on raw fd 1 (skips the LineWriter)200 ns164 ns491 ns8,615
C printf (reference)354 ns302 ns1,644 nsn/a

The things worth knowing:

  1. Taking the lock yourself does nothing. stdout().lock() with writeln! costs the same as println! (2,155 vs 2,026 ns per line to a file). The cost is the system call, not the mutex.
  2. BufWriter makes 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.
  3. eprintln! is the slowest way to log. stderr has no buffer at all, so one line becomes about 14 write(2) calls, one per formatted piece. It is 114x slower than BufWriter to a file.
  4. Wrapping stdout in a BufWriter still splits writes. The LineWriter under it holds back each partial line, so you get twice as many calls as you would expect (16,743 instead of about 8,600).
  5. std::process::exit loses the tail. A BufWriter that 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.

Bar chart of time per log line for seven ways of writing 1,000,000 lines, each to a file, a pipe and a terminal, Apple M2 Pro, rustc 1.95.0, median of 5 runs. println! 2,026 ns to a file, 732 ns to a pipe, 1,648 ns to a terminal. stdout().lock() with writeln! 2,155, 742 and 1,532 ns. BufWriter 8 KiB 233, 167 and 527 ns. BufWriter 64 KiB 227, 144 and 474 ns. BufWriter with format! per line 237, 189 and 532 ns. BufWriter on raw fd 1 200, 164 and 491 ns. C printf 354, 302 and 1,644 ns.

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.

Terminal panel titled syscount.dylib: write(2) calls per million lines, output of write-calls.tsv for the file sink. println 1,000,000 writes, eprintln 14,110,590, lock 1,000,000, bufwriter 16,743, bufwriter_64k 2,101, bufwriter_format 8,811, bufwriter_fd1 8,615, bufwriter_exit 16,742 writes; every variant wrote 70,536,967 bytes except bufwriter_exit with 70,536,604.

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:

Two CPU flame graphs from macOS sample, 4 seconds at 1 ms, of iobench writing into a pipe. Top, println!: 2,416 samples, and the widest frame at the top of the stack is write, the system call, under BufWriter flush_buf, StdoutLock write_all, core::fmt::write and std::io::stdio::_print. Bottom, BufWriter: 2,838 samples, spread across core::fmt::write, integer and float formatting and memmove, with write only a minority.

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:

Terminal panel: iobench write bufwriter_exit 1000000 into exit.out, a BufWriter followed by std::process::exit(0). exit.txt shows expected_bytes 70,536,967, written_bytes 70,536,604, expected_lines 1,000,000 and written_lines 999,994. The last bytes of the file end mid-line at req=0999994 with ms=1260. cut off, while the flushed run ends with req=0999999.

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):

Bar chart of time per line to read a 1,000,000-line, 70.5 MB log from stdin, median of 5 runs. .lines() with a new String per line 117.1 ns and 1.01 allocations per line; read_line into one String 78.9 ns; read_until into one Vec of u8 69.6 ns; read_to_string once then .lines() 71.6 ns; a BufReader around a File with .bytes() 246.1 ns. File.bytes() with no BufReader took 37,672 ns per line, 160x the buffered one, with 1,410,414 read calls for 1,410,413 bytes, measured on the first 20,000 lines only.

  • .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 with read_line makes it 78.9 ns. read_until(b'\n') into a Vec<u8> also skips the UTF-8 check and takes 69.6 ns. That is 1.7x faster for a two-line change.
  • read_to_string is as fast as read_until, 71.6 ns, with 24 read calls 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 a BufReader makes one read(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 a BufReader. 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

  1. A program that prints more than a few hundred lines writes through let mut out = BufWriter::new(io::stdout().lock()); and calls out.flush()? at the end. That is two lines of code, and the output gets 3x to 9x faster depending on where it goes.
  2. Locking stdout yourself without a BufWriter is not an optimisation.
  3. eprintln! in a loop is the slowest way to log in Rust. It is fine for errors, not for progress output or log streams.
  4. Never call std::process::exit while a BufWriter is alive. Flush first, or return an ExitCode.
  5. Read lines with read_line or read_until into a reused buffer, not .lines(). Never call .bytes() on an unbuffered File.
  6. Measure with a system-call count before you tune anything else. One write(2) per line was 90% of println!’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.

This post is licensed under CC BY 4.0 by the author.