go test benchmark 性能分析

青旅半醒 2022-11-21 15:27 262阅读 0赞

1、benchmark

新建文件以_test.go结尾

新增函数,以Benchmark开头

源码:

  1. package main
  2. import "testing"
  3. func BenchmarkTest(b *testing.B) {
  4. b.ResetTimer()
  5. for i:=0; i<b.N; i++ {
  6. Print()
  7. }
  8. //runtime.GC()
  9. }
  10. func Print() {
  11. //测试代码
  12. }

接下来就可以benchmark

  1. go test -bench=. -benchmem

结果:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L05MU1FR_size_16_color_FFFFFF_t_70

2、性能分析-pprof

命令:

  1. go test -bench=. -benchmem -memprofile memprofile.out -cpuprofile profile.out

执行后会生成两个文件,cpu和内存相关分析的问题

  1. go tool pprof -pdf profile.out > cpu.pdf
  2. go tool pprof -pdf memprofile.out > mem.pdf

执行这两个命令后,会生成性能分析图

保证环境安装了,graphviz可视化软件,以下命令安装graphviz

  1. brew install graphviz

性能分析结果:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L05MU1FR_size_16_color_FFFFFF_t_70 1

发表评论

表情:
评论列表 (有 0 条评论,262人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Go基准测试Benchmark

    > Go语言自带了一个强大的测试框架,其中包括基准测试(Benchmark)功能,基准测试用于测量和评估一段代码的性能。 我们可以通过在Go的测试文件中编写特殊格式的函数来创

    相关 go test 下篇

    前言 go test [上篇][Link 1] 给大家介绍了golang自带的测试框架,包括单元测试和性能测试。但是在实际生产中测试经常会遇到一些网络或者依赖的第三方系统