在 Linux 下,你可以使用 Go 语言内置的 testing
包和 pprof
工具来进行性能测试。以下是一些步骤和示例:
main.go
:package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
// 模拟一些工作负载
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
fmt.Printf("Worker %d finished\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
}
go test
命令进行性能测试。首先,创建一个名为 main_test.go
的测试文件:package main
import (
"testing"
"time"
)
func BenchmarkMain(b *testing.B) {
for i := 0; i < b.N; i++ {
main()
}
}
go test -bench=. -benchmem
这将输出程序的运行时间和内存分配情况。
pprof
工具。首先,在程序中导入 net/http/pprof
包,并启动 HTTP 服务器:package main
import (
"fmt"
"math/rand"
"net/http"
_ "net/http/pprof" // 导入 pprof 包
"sync"
"time"
)
// ... 其他代码保持不变 ...
go run main.go
使用 curl
或浏览器访问 http://localhost:6060/debug/pprof/
,你将看到可用的性能分析选项。例如,要查看 CPU 分析,请访问 http://localhost:6060/debug/pprof/profile?seconds=30
。这将收集 30 秒的 CPU 分析数据。
使用 go tool pprof
分析收集到的数据:
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
pprof
交互式命令行中,你可以使用各种命令来查看和分析性能数据,例如:top
:显示最耗时的函数list <function>
:显示指定函数的详细信息web
:生成 SVG 格式的调用图quit
退出 pprof
。通过这些步骤,你可以在 Linux 下使用 Go 语言进行性能测试和分析。