禁止在 golang 中内联
forbid inlining in golang
有什么方法可以指示 go 编译器不内联吗?
$ cat primes.go
package main
import ("fmt")
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
我猜 - 它存在吗?
您可以使用 //go:noinline
pragma 来禁用特定函数的内联。将它放在您希望应用它的功能之前:
//go:noinline
func isPrime(p int) bool {
// ...
}
如果你想禁用所有内联,你可以使用 -gcflags=-l
标志,例如:
go build -gcflags=-l primes.go
查看相关博客post:Dave Cheney: Mid-stack inlining in Go
你可以看看golang的编译文档
//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.
简而言之,您只需要在 isPrime 函数上方的行中添加 //go:noinline
。
//go:noinline
func isPrime(p int) bool {
// ...
}
有什么方法可以指示 go 编译器不内联吗?
$ cat primes.go
package main
import ("fmt")
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
我猜 - 它存在吗?
您可以使用 //go:noinline
pragma 来禁用特定函数的内联。将它放在您希望应用它的功能之前:
//go:noinline
func isPrime(p int) bool {
// ...
}
如果你想禁用所有内联,你可以使用 -gcflags=-l
标志,例如:
go build -gcflags=-l primes.go
查看相关博客post:Dave Cheney: Mid-stack inlining in Go
你可以看看golang的编译文档
//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.
简而言之,您只需要在 isPrime 函数上方的行中添加 //go:noinline
。
//go:noinline
func isPrime(p int) bool {
// ...
}