使用 Cargo 获取执行时间

reb*_*ing 0 time command-line rust rust-cargo

我对 Rust 很陌生,我想为我的程序的执行计时。我在网上搜索,但到目前为止一无所获。运行后cargo build,我的代码是这样执行的:

bling@bling ~/github/rust/hello_world [master *]
± % ./target/debug/hello_world
Run Code Online (Sandbox Code Playgroud)

Cargo 是否有内置的方式来计时执行还是我需要使用命令行?

Mic*_*den 5

您可以使用time,它是一个命令行实用程序。

$ time ./target/debug/hello_world
./target/debug/hello_world  3.02s user 0.18s system 34% cpu 9.177 total
Run Code Online (Sandbox Code Playgroud)

那将是最简单的方法。我认为您不能cargo直接传递标志来为编译步骤计时。

有类似的东西:cargo bench它允许您为您的程序编写基准测试。这会为您提供有关程序某些部分速度的非常具体的报告。

文档有更多阅读

$ cargo bench
running 1 test
test bench_xor_1000_ints ... bench:       131 ns/iter (+/- 3)
Run Code Online (Sandbox Code Playgroud)

尽管这仅在夜间 Rust 上可用。


She*_*ter 5

Cargo 没有内置的计时方式。您将需要使用您的操作系统机制。例如,在 Linux 或 macOS 上,您可能可以使用time(我自己使用hyperfine):

time ./target/debug/hello_world
Run Code Online (Sandbox Code Playgroud)

特别值得注意的是,您有一个调试版本。这没有优化,不应该用于分析。相反,您应该在发布模式下构建代码:

cargo build --release
Run Code Online (Sandbox Code Playgroud)

然后执行该target/release目录下的程序。

另外,您可能不想包括 Cargo 本身的时间。也就是说,不要执行以下任一操作:

time cargo run
time cargo run --release
Run Code Online (Sandbox Code Playgroud)