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

与Python代码相比,如何提高我的Rust代码的性能?,python,python-3.x,performance,rust,Python,Python 3.x,Performance,Rust,如何提高我的Rust代码的性能,因为Python大约需要5秒才能完成,Rust大约需要7秒 我正在使用build--release 防锈代码 fn main(){ 设mutn=0; 环路{ n+=1; println!(“n的值为{},&n); 如果n==100000{ 打破 } } } Python3代码 n=0 尽管如此: n+=1 打印(“n的值为”,n) 如果n==100000: 打破 如果我没记错,println会锁定stdout。摘自: […]默认的打印宏将为每个写入操作锁定标准输

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

我正在使用
build--release

防锈代码

fn main(){
设mutn=0;
环路{
n+=1;
println!(“n的值为{},&n);
如果n==100000{
打破
}
}
}
Python3代码

n=0
尽管如此:
n+=1
打印(“n的值为”,n)
如果n==100000:
打破

如果我没记错,
println
会锁定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


删除打印语句?
build--release
不是Rust命令。你的意思是
货物构建-发布
?切向地,不需要
&n
:如何计算时间?没有任何类型的打印,我希望Rust程序完全优化到与
fn main(){}
相当的程度。