简体   繁体   English

与 Python 代码相比,我如何提高 Rust 代码的性能?

[英]How can I improve the performance of my Rust code compared to Python code?

How can I improve the performance of my Rust code as Python takes around 5 seconds to finish and Rust takes 7 seconds.如何提高我的 Rust 代码的性能,因为 Python 需要大约 5 秒才能完成,而 Rust 需要 7 秒。

I am using build --release我正在使用build --release

Rust code Rust代码

fn main() {
    let mut n = 0;

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

Python3 code Python3 代码

n = 0
while True:
   n+=1
   print("The value of n is ",n)
   if n == 100000:
       break

If I recall correctly, println locks stdout.如果我没记错的话, println会锁定标准输出。 Taken from Rust Performance Pitfalls :取自Rust 性能缺陷

[...] the default print! [...] 默认print! macros will lock STDOUT for each write operation .宏将为每个写操作锁定 STDOUT。 So if you have a larger textual output (or input from STDIN), you should lock manually.因此,如果您有较大的文本 output(或从 STDIN 输入),则应手动锁定。

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.锁定和解锁 io::stdout 很多,并对标准输出和文件进行线性数量(可能很小)的写入。 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.这仅锁定一次,并且仅在缓冲区填满(或 buf 关闭)时写入,因此它应该更快。

Similarly, for network IO, you may want to use buffered IO.同样,对于网络 IO,您可能希望使用缓冲 IO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM