本文介绍了如果“cargo build",我为什么要使用 Cargo比直接运行 rustc 慢吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的 hello world 程序:

fn main() {println!("你好,世界");}

当使用 rustccargo build 编译代码时,cargo 命令显得更慢.cargo build 需要 1.6s,而 rustc 需要 1s.查看屏幕截图右侧的时间戳.

这是为什么?为什么我还要使用货物?

解决方案

正如 Pavel Strakhov 所说

Cargo 不是编译器,而是包管理器.它运行 rustc 并做一些额外的工作(例如解决依赖关系),所以它不能比裸 rustc 快.

您可以通过运行 cargo build --verbose 亲眼看到这一点,它会输出货物运行的 rustc 命令:

$ cargo build --verbose编译硬件 v0.1.0 (file:///private/tmp/hw)运行 `rustc --crate-name hw src/main.rs --crate-type bin --emit=dep-info,link -C debuginfo=2 -C metadata=3c693c67d55ff970 -C extra-filename=-3c693c67d55ff970 --out-dir/private/tmp/hw/target/debug/deps -L dependency=/private/tmp/hw/target/debug/deps`在 0.30 秒内完成开发 [未优化 + 调试信息] 目标

我为什么还要用cargo

上面的输出显示了一个原因:查看所有传递给 rustc 的参数.你知道他们每个人是做什么的吗?你知道吗?Cargo 抽象了一些细节,让您可以专注于代码.

Cargo 还不仅仅是调用编译器.对大多数人来说最大的好处是它根据版本管理你的依赖并允许也发布您自己的 crates.它还允许在主要编译之前运行的构建脚本.它有运行测试和示例的简单方法.

更直接有用的是,Cargo 会检查是否应该重建:

$ time rustc src/main.rs0:00.21$ 时间 rustc src/main.rs0:00.22$时间货物建造0:00.41$时间货物建造0:00.09 # 好多了!

I created a simple hello world program:

fn main() {
    println!("Hello, world");
}

When compiling the code using rustc vs cargo build, the cargo command appears slower. It takes 1.6s for cargo build vs 1s for rustc. See the timestamps on the right in the screenshot.

Why is this? Why should I still use cargo?

解决方案

As Pavel Strakhov said

You can see this for yourself by running cargo build --verbose, which outputs the rustc command that cargo runs:

$ cargo build --verbose
   Compiling hw v0.1.0 (file:///private/tmp/hw)
     Running `rustc --crate-name hw src/main.rs --crate-type bin --emit=dep-info,link -C debuginfo=2 -C metadata=3c693c67d55ff970 -C extra-filename=-3c693c67d55ff970 --out-dir /private/tmp/hw/target/debug/deps -L dependency=/private/tmp/hw/target/debug/deps`
    Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs

The output above shows one reason: Look at all those arguments passed to rustc. Do you know what each of them does? Do you want to know? Cargo abstracts some of the details away, allowing you to concentrate on the code.

Cargo also does so much more than just invoking the compiler. The biggest benefit to most people is that it manages your dependencies based on versions and allows publishing your own crates as well. It also allows for build scripts which run before your main compilation. It has easy ways of running your tests and examples.

More immediately useful, Cargo performs a check to see if you should rebuild at all:

$ time rustc src/main.rs
0:00.21
$ time rustc src/main.rs
0:00.22

$ time cargo build
0:00.41
$ time cargo build
0:00.09                   # Much better!

这篇关于如果“cargo build",我为什么要使用 Cargo比直接运行 rustc 慢吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 11:34