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

#1

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

Am I making obvious mistakes?

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

Cheers,
Guillem

#2

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.

4 Likes
#3

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
#4

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: