Guessing game (with a twist): how can I make it faster?

Hi,

I took the "guessing game" from a tutorial and turned it into a simple benchmark. It plays against itself to guess the first million integers. The thing is... I've got the "same" algorithm in Rust and in Go, and I don't know why the Rust version is much slower (2.93 seconds vs 0.25 on my laptop).

https://gist.github.com/guillem/28cf6fbe8db8990e10c47f6c6692591d

Am I making obvious mistakes?

BTW, first post and first contact with Rust, so... O:)

Cheers,
Guillem

First, make sure you are running with optimizations enabled. Use this command: cargo run --release

Second, you can use buffered output, as the go program does:

    use std::io::BufWriter
    let mut out = BufWriter::new(io::stdout());

Together, these changes reduced the runtime from 2.1s to 0.25s on my laptop.

6 Likes

You could lock Stdout, but it didn't make much difference for me when using a BufWriter.

I would also avoid the string temporary:

-        out.write(secret.to_string().as_bytes()).unwrap();
+        write!(out, "{}", secret).unwrap();

I guess you can do the same in Go with fmt.Fprintf.

2 Likes

Oh. Yeah. Especially the buffered output did the trick. And now it's a fair comparison because I was (unconsciously) already doing that in the Go version. Now they're neck to neck. Thank you :smiley:

2 Likes

I once made a repo to bench this https://github.com/rofrol/rust-regex-stdin-by-line-benchmark