使用 Cargo 获取执行时间
Getting execution time with Cargo
我是 Rust 的新手,我想为程序的执行计时。我在网上搜索,但到目前为止一无所获。在运行cargo build
之后,我的代码是这样执行的:
bling@bling ~/github/rust/hello_world [master *]
± % ./target/debug/hello_world
Cargo 是否有内置的执行时间方式,或者我是否需要使用命令行?
您可以使用 time
,它是一个命令行实用程序。
$ time ./target/debug/hello_world
./target/debug/hello_world 3.02s user 0.18s system 34% cpu 9.177 total
这将是最简单的方法。我认为您不能将标志直接传递给 cargo
来为编译步骤计时。
有类似的东西:cargo bench
它允许你为你的程序编写基准。这会为您提供有关程序某些部分速度的非常具体的报告。
$ cargo bench
running 1 test
test bench_xor_1000_ints ... bench: 131 ns/iter (+/- 3)
尽管这仅适用于 nightly Rust。
Cargo 没有内置的计时方式。您将要使用您的操作系统机制。例如,在 Linux 或 OS X 上,您可能可以使用 time
:
time ./target/debug/hello_world
需要特别注意的是,您有一个 调试 构建。此 没有优化 ,不应该用于分析。相反,您应该在发布模式下构建代码:
cargo build --release
然后执行target/release
目录下的程序
此外,您可能不想包括 Cargo 本身的时间。也就是说,不要做以下任一操作:
time cargo run
time cargo run --release
它没有被烘焙成货物,但 hyperfine 是用铁锈写成的,是时间的替代品:
cargo install hyperfine
hyperfine ./target/debug/hello_world
我是 Rust 的新手,我想为程序的执行计时。我在网上搜索,但到目前为止一无所获。在运行cargo build
之后,我的代码是这样执行的:
bling@bling ~/github/rust/hello_world [master *]
± % ./target/debug/hello_world
Cargo 是否有内置的执行时间方式,或者我是否需要使用命令行?
您可以使用 time
,它是一个命令行实用程序。
$ time ./target/debug/hello_world
./target/debug/hello_world 3.02s user 0.18s system 34% cpu 9.177 total
这将是最简单的方法。我认为您不能将标志直接传递给 cargo
来为编译步骤计时。
有类似的东西:cargo bench
它允许你为你的程序编写基准。这会为您提供有关程序某些部分速度的非常具体的报告。
$ cargo bench
running 1 test
test bench_xor_1000_ints ... bench: 131 ns/iter (+/- 3)
尽管这仅适用于 nightly Rust。
Cargo 没有内置的计时方式。您将要使用您的操作系统机制。例如,在 Linux 或 OS X 上,您可能可以使用 time
:
time ./target/debug/hello_world
需要特别注意的是,您有一个 调试 构建。此 没有优化 ,不应该用于分析。相反,您应该在发布模式下构建代码:
cargo build --release
然后执行target/release
目录下的程序
此外,您可能不想包括 Cargo 本身的时间。也就是说,不要做以下任一操作:
time cargo run
time cargo run --release
它没有被烘焙成货物,但 hyperfine 是用铁锈写成的,是时间的替代品:
cargo install hyperfine
hyperfine ./target/debug/hello_world