14.1 cargo:发布配置
14.1.1 Release Profile
Release profile 是发布配置的意思,它是一系列预定好的配置方案。而且它是可自定义的,我们可以自定义配置并使用不同的设置,从而让程序员对代码的编译有更多的控制权。
每个 profile 就是各自的配置档案,独立于其它的 profile。
在 Cargo 里主要有两个 profile:
dev profile:适用于开发、cargo buildrelease profile:适用于发布、cargo build --release
使用 cargo build 和 cargo build --release 指令会应用两个不同的配置档案:
$ cargo build
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
$ cargo build --release
Finished `release` profile [optimized] target(s) in 0.00s
14.1.2 自定义 Profile
针对每个 profile,Cargo 都提供了默认的配置。
如果想要自定义配置(不论是 dev profile 还是 release profile),可以在 Cargo.toml 里添加 [profile.xxxx] 区域,在里面覆盖默认配置的子集。通常我们不会覆盖所有的选项,只需要覆盖那些想修改的配置。
看个例子:
[profile.dev]
opt-level = 0
[profile.release]
opt-level = 3
opt-level 设置控制 Rust 将应用于你的代码的优化数量,范围为 0 到 3。应用更多优化会延长编译时间,因此,如果你经常进行开发和编译代码,即使生成的代码运行速度较慢,你也可能希望使用更少的优化,因为这样可以加快编译速度。因此 dev 的默认 opt-level 是 0。
当准备好发布代码时,最好花更多时间进行编译。代码只会在发布模式下编译一次,但会多次运行编译后的程序,因此发布模式会用更长的编译时间换取运行速度更快的代码。这就是为什么 release 的默认 opt-level 是 3。