这个是用来进行http接口压测的
官网地址:https://github.com/tsliwowicz/go-wrk
七牛云下载
使用
go-wrk -d 500 http://localhost:8080/hello
go get github.com/uber/go-torch
官网下载地址:https://www.activestate.com/products/perl/downloads/
七牛云下载
注意
:安装时记得把添加到环境变量PATH选项勾上
git clone https://github.com/brendangregg/FlameGraph.git
注意
:将此文件夹加入到PATH
环境变量中
生成SVG 图,能够更好地看到函数调用 CPU 占用情况
官网下载地址:https://graphviz.gitlab.io/_pages/Download/Download_windows.html
七牛云下载
安装好之后,添加其 bin文件到PATH
环境变量中
# Ubuntu
sudo apt-get install graphviz
# Centos
yum install graphviz
检查是否安装成功
dot -version
开启性能分析只需要导入下面这个包即可
import _ "net/http/pprof"
代码见文章末尾附录
main.go
go-wrk -d 500 http://localhost:8080/hello
浏览器打开:http://localhost:8080/debug/pprof/
allocs
: 内存分配情况block
: 导致阻塞同步的堆栈跟踪cmdline
: 当前程序激活的命令行goroutine
: 当前运行的goroutineheap
: 存活对象的内存分配情况mutex
: 互斥锁的竞争持有者的堆栈跟踪profile
: 默认进行 30s 的 CPU Profilingthreadcreate
: 操作系统线程跟踪trace
: 当前程序执行情况full goroutine stack dump
: 所有goroutine栈输出下面命令会打开一个交互页面
go tool pprof --seconds 5 http://localhost:8080/debug/pprof/profile
常用命令
top
默认显示 10 个占用 CPU 时间最多的函数tree
树形结构查看goroutine情况。web
生成SVG函数调用图(需安装graphviz
)exit
退出分析打开pprof
可视化页面,与上面 可交互页面中web
命令效果一样
go tool pprof -http=:8080 http://localhost:8080/debug/pprof/profile?seconds=60
进行 5 秒钟的 CPU 性能采样并生成火焰图
go-torch --seconds 5 http://localhost:8080/debug/pprof/profile
命令执行完会在该目录下生成一个torch.svg
文件,可用浏览器打开查看火焰图
pprof.cpu
文件go test -bench . -benchmem -cpuprofile pprof.cpu
pprof.cpu
文件go tool pprof pprof.cpu
package main
import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"path/filepath"
"time"
"github.com/varstr/uaparser"
)
const hostPort = ":8080"
func main() {
http.HandleFunc("/hello", Hello)
fmt.Println("Starting server on", hostPort)
if err := http.ListenAndServe(hostPort, nil); err != nil {
log.Fatalf("HTTP server failed: %v", err)
}
}
func Hello(w http.ResponseWriter, r *http.Request) {
start := time.Now()
tags := getStatsTags(r)
duration := time.Since(start)
fmt.Println(tags, duration)
}
func getStatsTags(r *http.Request) map[string]string {
userBrowser, userOS := parseUserAgent(r.UserAgent())
stats := map[string]string{
"browser": userBrowser,
"os": userOS,
"endpoint": filepath.Base(r.URL.Path),
}
hostName, _ := os.Hostname()
if hostName != "" {
stats["host"] = hostName
}
return stats
}
func parseUserAgent(uaString string) (browser, os string) {
ua := uaparser.Parse(uaString)
if ua.Browser != nil {
browser = ua.Browser.Name
}
if ua.OS != nil {
os = ua.OS.Name
}
return browser, os
}