Skip to content

Improve seeding and initialize thread-local non-determinism with fresh entropy#48

Open
orlp wants to merge 4 commits into
masterfrom
seed-improve
Open

Improve seeding and initialize thread-local non-determinism with fresh entropy#48
orlp wants to merge 4 commits into
masterfrom
seed-improve

Conversation

@orlp

@orlp orlp commented Jul 3, 2026

Copy link
Copy Markdown
Owner

Fixes #47.

@orlp

orlp commented Jul 3, 2026

Copy link
Copy Markdown
Owner Author

@hoxxep Want to take a look?

@hoxxep

hoxxep commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

The logic looks sound. My only thought would be that it does 11 mixes, two syscalls, an allocation, and an atomic load/store for every new thread, which seems like a lot? It's much more straightforward to reason about than my approach though, so it LGTM.

@orlp

orlp commented Jul 3, 2026

Copy link
Copy Markdown
Owner Author
use std::time::Duration;

fn main() {
    let iters = 1_000_000;
    let mut times = [0.0; 2];
    for iter in 0..iters {
        let start = std::time::Instant::now();
        std::thread::scope(|s| {
            s.spawn(|| {
                if iter % 2 == 1 {
                    core::hint::black_box(foldhash::quality::RandomState::default());
                }
                times[iter % 2] += start.elapsed().as_secs_f64();
            });
        });
    }
    
    let without = Duration::from_secs_f64(times[0] / iters as f64);
    let with = Duration::from_secs_f64(times[1] / iters as f64);
    let overhead = with - without;
    eprintln!("Without: {without:?}");
    eprintln!("With: {with:?}");
    eprintln!("Overhead: {overhead:?} ({:.2}%)", 100.0 * (times[1] / times[0] - 1.0));
}

On my Apple M2 this prints:

Without: 5.993µs
With: 6.126µs
Overhead: 133ns (2.22%)

I'm honestly surprised the thread spawn is even remotely that fast. And if you care about 0.1us latency on a thread spawn you're probably doing things wrong and should have a pre-spawned thread pool anyway.

@hoxxep

hoxxep commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Good point, it looks good to me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RandomState with the std feature enabled doesn't produce random seeds on new threads

2 participants