gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:35:51 26 4
gpt4 key购买 nike

我如何提高我的 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 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.

关于python - 与 Python 代码相比,我如何提高 Rust 代码的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58491486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com