禁止在Golang中进行内联操作。

huangapple go评论68阅读模式
英文:

forbid inlining in golang

问题

有没有办法指示Go编译器内联?

$ cat primes.go
package main
import "fmt"

//go:noinline
func isPrime(p int) bool {
    for i := 2; i < p; i += 1 {
        for j := 2; j < p; j += 1 {
            if i*j == p {
                return false
            }
        }
    }
    return true
}

func main() {
    for p := 2; p < 100; p+= 1 {
        if isPrime(p) {
            fmt.Println(p)
        }
    }
}
$ go build primes.go
$ objdump -D -S primes > primes.human
$ grep -rn "isPrime" primes.human
210091:        if isPrime(p) {

我猜相当于gcc -O0,它存在吗?

英文:

is there any way to instruct the go compiler to not inline?

$ cat primes.go
package main
import (&quot;fmt&quot;)

func isPrime(p int) bool {
    for i := 2; i &lt; p; i += 1 {
        for j := 2; j &lt; p; j += 1 {
            if i*j == p {
                return false
            }
        }
    }
    return true
}

func main() {
    for p := 2; p &lt; 100; p+= 1 {
        if isPrime(p) {
            fmt.Println(p)
        }
    }
}
$ go build primes.go
$ objdump -D -S primes &gt; primes.human
$ grep -rn &quot;isPrime&quot; primes.human
210091:        if isPrime(p) {

the equivalent to gcc -O0 I guess - does it exist?

答案1

得分: 11

你可以使用//go:noinline指令来禁止特定函数的内联。将其放置在你希望应用该指令的函数之前:

//go:noinline
func isPrime(p int) bool {
    // ...
}

如果你想禁止所有的内联操作,你可以使用-gcflags=-l标志,例如:

go build -gcflags=-l primes.go

相关博文请参考:Dave Cheney: Go中的中间栈内联

英文:

You may use the //go:noinline pragma to disable inlining of specific functions. Place it before the function you wish to apply it on:

//go:noinline
func isPrime(p int) bool {
    // ...
}

If you want to disable all inlinings, you may use the -gcflags=-l flag, e.g.:

go build -gcflags=-l primes.go

See related blog post: Dave Cheney: Mid-stack inlining in Go

答案2

得分: 5

你可以阅读关于golang编译的文档。

godoc/compile

> //go:noinline
>
> //go:noinline指令必须跟在函数声明后面。它指定函数调用不应该被内联,覆盖编译器的通常优化规则。通常只有在特殊的运行时函数或调试编译器时才需要使用。

简而言之,你只需要在isPrime函数上面的那一行添加//go:noinline

//go:noinline
func isPrime(p int) bool {
    // ...
}
英文:

You can read the documentation of golang about compile

godoc/compile

> //go:noinline
>
> The //go:noinline directive must be followed by a function declaration. It specifies that calls to the function should not be inlined, overriding the compiler's usual optimization rules. This is typically only needed for special runtime functions or when debugging the compiler.

In short, you only need to add //go:noinline to the line above your isPrime function.

//go:noinline
func isPrime(p int) bool {
    // ...
}

huangapple
  • 本文由 发表于 2021年7月7日 13:57:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/68280753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定