dovhpmnm31216 2017-12-08 12:18
浏览 2593
已采纳

为什么用CGO_ENABLED = 0编译慢?

When writing programs which utilize network, you can see quite noticeable slowdown of compilation with CGO_ENABLED=0.

For example, the simplest HTTP server:

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi! glad you requested %s.
", r.URL.Path[1:])
}

func main() {
    port := flag.Int("port", 9000, "")
    flag.Parse()

    http.HandleFunc("/", handler)
    err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
    if err != nil {
        log.Fatal(err)
    }
}

the timings are:

% time go build
go build  0.46s user 0.06s system 131% cpu 0.396 total
% time CGO_ENABLED=0 go build
CGO_ENABLED=0 go build  3.93s user 0.15s system 143% cpu 2.849 total

So far I'm not using bindings to C so CGo handling or not seems irrelevant, what I'd like to do is to compile 100% static binary, but not if there's such slowdown.

What is the cause of such behavior?

  • 写回答

2条回答 默认 最新

  • dongzhang8680 2017-12-08 14:06
    关注

    The problem is that the standard library packages are built without flags. CGO_ENABLED changes build flags and therefore it can't use the pre-built packages so most of the standard library needs to be rebuilt.

    As the other answer mentioned, go build -i will install the packages built with the new flags, but that won't really solve much because if you install packages built with CGO_ENABLED=0, it will speed up all future builds with CGO_ENABLED=0, but it will slow down all the builds without it.

    Unfortunately the way pre-built packages are installed by default today is pretty inefficient because everything goes into the same directory under the same names regardless of how it's built. If you want to be able to have fast builds of go programs with different flags, besides doing go build -i you also need to use the the -installsuffix and/or the -pkgdir flags. In the system I work in, we have a handful of different compilation modes, each mode has different flags (because of a lot of old C code we interface with) and each mode also has its own -pkgdir.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch