bigywater.tech
Rust · 155

Cargo Profile

上一篇比较了 debug 与 release 的速度,这一篇换一个角度:profile 到底在配置什么?它们真实传给 rustc 的参数是什么?怎样给依赖单独调优、自定义 profile、调整调试信息?全部用 cargo -v 的输出和真实文件大小回答。

-v
用 cargo build -v 直接看 profile 展开成 rustc 的 -C 参数
inherits
自定义 profile 继承 dev 并覆盖个别配置
916 → 1442 KB
debug = 0 与 2 时整个 target/release 目录的大小(二进制本身几乎不变)

profile 展开成什么参数

实测 · 本机执行输出
  dev              → ['debuginfo=2', 'embed-bitcode=no', 'incremental=<实验目录>/target/debug/incremental']
  release          → ['embed-bitcode=no', 'opt-level=3', 'strip=debuginfo']
  test(cargo test) → ['debuginfo=2', 'embed-bitcode=no', 'incremental=<实验目录>/target/debug/incremental']

dev 与 release 的耗时对比见Debug 与 Release 构建差异;LTO 与体积见LTO 与二进制体积。

给依赖单独调优

实测 · 本机执行输出
  itoa(依赖)  → ['debug-assertions=on', 'debuginfo=2', 'embed-bitcode=no', 'opt-level=3']
  u155(自己)  → ['debuginfo=2', 'embed-bitcode=no', 'incremental=<实验目录>/target/debug/incremental']

自定义 profile

实测 · 本机执行输出
  fastdev → ['debug-assertions=on', 'embed-bitcode=no', 'incremental=<实验目录>/target/fastdev/incremental', 'opt-level=2', 'strip=debuginfo']
  产物目录:['fastdev'](target/fastdev 是单独的目录)
  不存在的 profile: ['error: profile `nonexistent` is not defined']

调试信息的级别

实测 · 本机执行输出
  debug = 0                    二进制   457,944 字节   整个 target/release 目录    916,974 字节
  debug = "line-tables-only"   二进制   461,032 字节   整个 target/release 目录  1,186,693 字节
  debug = 2                    二进制   461,032 字节   整个 target/release 目录  1,442,742 字节

macOS 的调试信息保存方式与 Linux 不同;这里的「二进制几乎不变」是 macOS 上的结果。

build-override

实测 · 本机执行输出
  build.rs(build_script_build)的 -C 参数 → ['debug-assertions=off', 'embed-bitcode=no', 'extra-filename=-497d791bf9e47b90', 'metadata=9a7c5efaf47ed1eb', 'strip=debuginfo'](没有 opt-level=,即默认的 0)
  目标代码 u155b → ['embed-bitcode=no', 'opt-level=3', 'strip=debuginfo']

build.rs 的更多行为见Build Script build.rs。

分步演示

Cargo Profile
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64 / rustc 1.98.1(brew)/ cargo 1.98.1;单个文件用 rustc 直接编译,需要依赖时用 cargo(经代理从 crates.io 下载);计时用 std::time::Instant,数字每次运行会有小幅抖动。macOS(split-debuginfo 默认 unpacked)
    • 没有验证:Linux 上 debug 级别对二进制大小的影响、split-debuginfo 取值的效果、[profile.*.package.NAME] 对单个依赖的覆盖、bench profile、PGO、[profile.release] panic = "abort" 对 test 的影响(cargo test 会忽略它)
    京ICP备2026067502号-1京公网安备11010502063487号