繁体   English   中英

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

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

如何提高我的 Rust 代码的性能,因为 Python 需要大约 5 秒才能完成,而 Rust 需要 7 秒。

我正在使用build --release

Rust代码

fn main() {
    let mut n = 0;

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

Python3 代码

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

如果我没记错的话, println会锁定标准输出。 取自Rust 性能缺陷

[...] 默认print! 宏将为每个写操作锁定 STDOUT。 因此,如果您有较大的文本 output(或从 STDIN 输入),则应手动锁定。

这个:

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

锁定和解锁 io::stdout 很多,并对标准输出和文件进行线性数量(可能很小)的写入。 加快速度:

 { 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>

这仅锁定一次,并且仅在缓冲区填满(或 buf 关闭)时写入,因此它应该更快。

同样,对于网络 IO,您可能希望使用缓冲 IO。

暂无
暂无

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

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