-2

How can I improve the performance of my Rust code as Python takes around 5 seconds to finish and Rust takes 7 seconds.

I am using build --release

Rust code

fn main() {
    let mut n = 0;

    loop {
        n += 1;
        println!("The value of n is {}", &n);
        if n == 100000 {
            break;
        }
    }
}

Python3 code

n = 0
while True:
   n+=1
   print("The value of n is ",n)
   if n == 100000:
       break
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Taza
  • 1

1 Answers1

5

If I recall correctly, println locks stdout. Taken from Rust Performance Pitfalls:

[...] the default print! macros will lock STDOUT for each write operation. So if you have a larger textual output (or input from STDIN), you should lock manually.

This:

let mut out = File::new("test.out");
println!("{}", header);
for line in lines {
    println!("{}", line);
    writeln!(out, "{}", line);
}
println!("{}", footer);

locks and unlocks io::stdout a lot, and does a linear number of (potentially small) writes both to stdout and the file. Speed it up with:

{
    let mut out = File::new("test.out");
    let mut buf = BufWriter::new(out);
    let mut lock = io::stdout().lock();
    writeln!(lock, "{}", header);
    for line in lines {
        writeln!(lock, "{}", line);
        writeln!(buf, "{}", line);
    }
    writeln!(lock, "{}", footer);
}   // end scope to unlock stdout and flush/close buf> 

This locks only once and writes only once the buffer is filled (or buf is closed), so it should be much faster.

Similarly, for network IO, you may want to use buffered IO.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
phimuemue
  • 34,669
  • 9
  • 84
  • 115