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



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

我正在使用build --release

锈代码

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

蟒蛇3代码

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

如果我没记错的话,println锁定了标准输出。摘自 Rust 性能陷阱:

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

这:

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

锁定和解锁 io::stdout 很多,并对 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。

最新更新