面试题答案
一键面试- 获取goroutine运行状态:
- 使用
runtime/debug
包:runtime/debug
包中的Stack
函数可以获取当前所有goroutine的栈跟踪信息。示例代码如下:
- 使用
package main
import (
"fmt"
"runtime/debug"
)
func main() {
go func() {
// 模拟一个运行的goroutine
for {
}
}()
stackInfo := debug.Stack()
fmt.Println(string(stackInfo))
}
- 使用
net/http/pprof
包:- 引入
net/http/pprof
包后,通过http
服务来查看goroutine相关信息。首先启动一个http
服务:
- 引入
package main
import (
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
// 模拟一个运行的goroutine
for {
}
}()
http.ListenAndServe(":6060", nil)
}
- 然后在浏览器中访问`http://localhost:6060/debug/pprof/goroutine?debug=1`,可以看到所有goroutine的详细信息,包括调用栈等。
2. 获取CPU和内存使用情况:
- 使用
runtime/pprof
包:- CPU Profiling:
- 以下是一个简单的示例来收集CPU性能分析数据:
- CPU Profiling:
package main
import (
"fmt"
"os"
"runtime/pprof"
)
func heavyWork() {
for i := 0; i < 1000000000; i++ {
// 模拟一些计算
_ = i * i
}
}
func main() {
f, err := os.Create("cpu.prof")
if err!= nil {
fmt.Println("Failed to create CPU profile file:", err)
return
}
defer f.Close()
err = pprof.StartCPUProfile(f)
if err!= nil {
fmt.Println("Failed to start CPU profile:", err)
return
}
defer pprof.StopCPUProfile()
heavyWork()
}
- 运行程序后,会生成`cpu.prof`文件。可以使用`go tool pprof cpu.prof`命令来分析该文件,通过交互界面查看CPU使用情况,例如使用`top`命令查看占用CPU最多的函数等。
- **Memory Profiling**:
- 示例代码如下:
package main
import (
"fmt"
"os"
"runtime/pprof"
)
func allocateMemory() {
data := make([]byte, 1024*1024*10) // 分配10MB内存
// 模拟使用内存
for i := range data {
data[i] = byte(i % 256)
}
}
func main() {
f, err := os.Create("mem.prof")
if err!= nil {
fmt.Println("Failed to create memory profile file:", err)
return
}
defer f.Close()
allocateMemory()
err = pprof.WriteHeapProfile(f)
if err!= nil {
fmt.Println("Failed to write memory profile:", err)
return
}
}
- 运行程序生成`mem.prof`文件,然后使用`go tool pprof mem.prof`命令来分析内存使用情况,例如查看哪些函数分配了最多的内存等。
- 使用
net/http/pprof
包:- 对于内存使用情况,启动
http
服务(如前面引入net/http/pprof
包的示例)后,在浏览器中访问http://localhost:6060/debug/pprof/heap
,可以查看堆内存使用情况的图形化展示。同时,http://localhost:6060/debug/pprof/profile
可以获取CPU性能分析数据,类似通过文件获取的方式,只不过这里是实时通过http
获取。
- 对于内存使用情况,启动