Skip to content

Commit

Permalink
Rollup merge of #99742 - sigaloid:master, r=thomcc
Browse files Browse the repository at this point in the history
Add comments about stdout locking

This is the source of some confusion regarding the `println!` macro:
* https://llogiq.github.io/2017/06/01/perf-pitfalls.html#unbuffered-io
* https://news.ycombinator.com/item?id=18794930
* https://reddit.com/r/rust/comments/5puyx2/why_is_println_so_slow/dcua5g5/
* https://reddit.com/r/rust/comments/ab7hsi/comparing_pythagorean_triples_in_c_d_and_rust/ecy7ql8/

In some of these cases it's not the locking behavior where the bottleneck lies, but it's still mentioned as a surprise when, eg, benchmarking a million `println!`'s in a very tight loop.

If there's any stylistic problems please feel free to correct me! This is my first contribution and I want to get it right 🦀
  • Loading branch information
GuillaumeGomez authored Aug 26, 2022
2 parents e3148dc + fab36d1 commit ae838f7
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions library/std/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,23 @@ macro_rules! panic {
/// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
/// immediately.
///
/// The `print!` macro will lock the standard output on each call. If you call
/// `print!` within a hot loop, this behavior may be the bottleneck of the loop.
/// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
/// ```
/// use std::io::{stdout, Write};
///
/// let mut lock = stdout().lock();
/// write!(lock, "hello world").unwrap();
/// ```
///
/// Use `print!` only for the primary output of your program. Use
/// [`eprint!`] instead to print error and progress messages.
///
/// [flush]: crate::io::Write::flush
/// [`println!`]: crate::println
/// [`eprint!`]: crate::eprint
/// [lock]: crate::io::Stdout
///
/// # Panics
///
Expand Down Expand Up @@ -75,11 +86,22 @@ macro_rules! print {
/// This macro uses the same syntax as [`format!`], but writes to the standard output instead.
/// See [`std::fmt`] for more information.
///
/// The `println!` macro will lock the standard output on each call. If you call
/// `println!` within a hot loop, this behavior may be the bottleneck of the loop.
/// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
/// ```
/// use std::io::{stdout, Write};
///
/// let mut lock = stdout().lock();
/// writeln!(lock, "hello world").unwrap();
/// ```
///
/// Use `println!` only for the primary output of your program. Use
/// [`eprintln!`] instead to print error and progress messages.
///
/// [`std::fmt`]: crate::fmt
/// [`eprintln!`]: crate::eprintln
/// [lock]: crate::io::Stdout
///
/// # Panics
///
Expand Down

0 comments on commit ae838f7

Please sign in to comment.