在Java中,我们用Junit做单元测试,用JMH做性能基准测试(benchmark),用async-profiler剖析cpu性能,用jstack、jmap、arthas等来排查问题。 作为一名比较新的编程语言,golang的这些工具是否更加好用呢? 单元测试Java的单元测试需要使用第三方库,一般是Junit,配置起来比较复杂。在使用了golang之后发现golang自带的单元测试真的非常简单。 如果我们有一个cal.go文件,那么其对应的单元测试文件为cal_test.go,其中的方法命名必须为TestXxx,这种按照命名进行单元测试的方式简单有效,也正是通常所说的“约定大于配置”。 来看一个简单的例子: package unit func add(a int, b int) int { return a + b } func sub(a int, b int) int { return a - b }
package unit import ( "github.com/stretchr/testify/assert" "testing" ) func TestAdd(t *testing.T) { assert.Equal(t, 10, add(5, 5)) } func TestSub(t *testing.T) { assert.Equal(t, 0, sub(5, 5)) }
执行单元测试只需要运行(更多用法参考go help test) go test --cover cal_test.go cal.go -v benchmark和单元测试类似,golang的benchmark也是开箱即用。在cal_test.go基础上增加一个BenchmarkAdd方法 package unit import ( "github.com/stretchr/testify/assert" "testing" ) func TestAdd(t *testing.T) { assert.Equal(t, 10, add(5, 5)) } func TestSub(t *testing.T) { assert.Equal(t, 0, sub(5, 5)) } func BenchmarkAdd(b *testing.B) { for i:= 0; i < b.N; i++ { add(5, 5) } }
pprofpprof是golang自带的可以用来做cpu、内存、锁分析的工具,非常类似java的async-profiler。 pprof的使用非常简单,只需要在代码中引入net/http/pprof包,然后监听一个端口即可。 一个简单的例子如下 package main import ( "fmt" "log" "net/http" "time" _ "net/http/pprof" ) func main() { go func() { //example: visit http://127.0.0.1:6060/debug/pprof in browser. err := http.ListenAndServe("0.0.0.0:6060", nil) if err != nil { fmt.Println("failed to start pprof goroutine:", err) } }() http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe("localhost:8000", nil)) } func handler(w http.ResponseWriter, r *http.Request) { time.Sleep(1 * time.Second) eat() time := time.Now().Unix() * 2 + 1000000 fmt.Fprintf(w, "URL.Path = %q; time = %d\n", r.URL.Path, time) } func eat() { loop := 10000000000 for i := 0; i < loop; i++ { // do nothing } }
此时可以使用top等命令直接查看cpu消耗过高的函数,更多命令可以使用help查看。
|