r/rust • • 22d ago

🙋 seeking help & advice Removing eprintln! made my hot loop 11 % slower. How do you control inlining in production Rust code? Or am I missing something?

Hi all. I am doing 1BRC and I needed to print something on console with eprintln!. I do a lot of measurements and my code wall time was 1.22 seconds on 8 CPU cores. So I wanted to commit my changes and before that I removed the eprintln! code. You know. But that change increased my code wall time to 1.36 seconds.

This is the code before (wall time 1.22 seconds with 170272167824 instructions:u):

fn one(map: &[u8], thread_number: usize) -> HashMap<StationName<'_>, MeasurementStats, IdealHasherBuilder> {
    let before = Instant::now();
    let mut stats: HashMap<StationName, MeasurementStats, IdealHasherBuilder> = HashMap::with_capacity_and_hasher(1_000, IdealHasherBuilder);
    for (station, temperature) in StationTemperatureIterator::new(map) {
        let t = parse_temperature(temperature);

        let stat = match stats.get_mut(&station) {
            Some(stat) => stat,
            None => stats.entry(station).or_insert(MeasurementStats::default())
        };
        stat.update(t);
    }
    eprintln!("Time (thread {}) - one: {}s", thread_number, before.elapsed().as_millis());
    stats
}

and this is the code after (wall time 1.36 seconds width 202165675453 instructions:u):

fn one(map: &[u8], thread_number: usize) -> HashMap<StationName<'_>, MeasurementStats, IdealHasherBuilder> {
    let before = Instant::now();
    let mut stats: HashMap<StationName, MeasurementStats, IdealHasherBuilder> = HashMap::with_capacity_and_hasher(1_000, IdealHasherBuilder);
    for (station, temperature) in StationTemperatureIterator::new(map) {
        let t = parse_temperature(temperature);

        let stat = match stats.get_mut(&station) {
            Some(stat) => stat,
            None => stats.entry(station).or_insert(MeasurementStats::default())
        };
        stat.update(t);
    }
    stats
}

objdump showed me that get_mut is inlined in the version with eprintln!. Without it get_mut is a call on every row. So I added:

RUSTFLAGS="-C llvm-args=-inline-threshold=1000"

To make it fast again (1.09 seconds even faster than with eprintln!) but it's not something I would do at work as this config is for whole program instead of the problematic section.

So:

  1. How do you handle this at work where performance matters?

  2. How do you catch this generally? Those 11% is huge difference.

Code link: https://github.com/davidhruby/brrr/blob/part012/src/david/main.rs#L350

82 Upvotes

29 comments sorted by

View all comments

Show parent comments

1

u/hrubydavid 10d ago

Thank you all for the comments 👏 I didn't know about PGO and it's very interesting. It showed me one missing cold path hint that improved my performance by 6.2% 😮 That's a lot since I couldn't find any new improvement today 😬 And it was so easy to use that I would put it into my CICD if there is need at work.