`go build` 不必要地重建 [英] `go build` rebuilds unnecessarily
问题描述
go build 和 go run 在我拥有的一个小程序上非常慢(尤其是 cgo 调用).我想缓存二进制文件,以便它只在源更新时重建.我会使用带有 % 规则的简单 Makefile,但语言设计者声称 go 的构建支持不需要 Makefile.
go build and go run are very slow on a tiny program I have (cgo invocations in particular). I'd like go to cache the binary so that it only rebuilds when the source is newer. I would use a simple Makefile with a % rule, but the language designers claim that go's build support doesn't need Makefiles.
还有我忽略的另一种选择吗?Go 社区是否更喜欢另一种构建系统(可能基于哈希)来缓存和重用构建产品?
Is there another alternative I've overlooked? Does the go community prefer another build system, maybe hash-based instead, for caching and reusing build products?
推荐答案
我写了一个工具作为副作用来解决这个问题.go build
单独不会检查它生成的可执行文件是否已经是最新的.go install
可以,如果您调整它以安装到您选择的位置,那么您将获得所需的结果,类似于 go build
.
I wrote a tool that happens to solve this as a side effect. go build
alone will not check if the executable it's producing is already up to date. go install
does, and if you tweak it to install to a location of your choice, then you'll get the desired result, similar to go build
.
您可以通过执行以下操作来查看您所描述的行为:
You can see the behaviour you describe by doing something like this:
$ go get -d github.com/anacrolix/missinggo/cmd/nop
$ time go run "$GOPATH"/src/github.com/anacrolix/missinggo/cmd/nop/*.go
real 0m0.176s
user 0m0.142s
sys 0m0.048s
这是一个温暖的运行.go run
将在每次调用时链接,就像 go build
一样.请注意,github.com/anacrolix/missinggo/cmd/nop
是一个什么都不做的程序.
That's on a warm run. go run
will link on every invocation, just as go build
would. Note that github.com/anacrolix/missinggo/cmd/nop
is an program that does absolutely nothing.
这里使用我的工具 godo 调用相同的包:
Here's invoking the same package, using my tool, godo:
$ time godo github.com/anacrolix/missinggo/cmd/nop
real 0m0.073s
user 0m0.029s
sys 0m0.033s
对于较大的程序,差异应该更明显.
For larger programs, the difference should be more pronounced.
总而言之,您的标准工具选项是使用 go install
,或者像 godo 这样的替代方法.
So in summary, your standard tooling option is to use go install
, or an alternative like godo.
这篇关于`go build` 不必要地重建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!