Go入门笔记38-Go Benchmark

1、以测试marshal和for循环为例
2、新建一个文件夹,添加代码

package main_test

import (
	"encoding/json"
	"fmt"
	"testing"
)

type A struct {
	ContentA string `json:"content_a"`
	ContentB string `json:"content_b"`
	ContentC string `json:"content_c"`
	ContentD string `json:"content_d"`
	ContentE string `json:"content_e"`
	ContentF string `json:"content_f"`
	ContentG string `json:"content_g"`
	ContentH string `json:"content_h"`
	ContentI string `json:"content_i"`
	ContentJ string `json:"content_j"`
	ContentK string `json:"content_k"`
	ContentL string `json:"content_l"`
}

type B struct {
	ContentA string `json:"content_a"`
	ContentB string `json:"content_b"`
	ContentC string `json:"content_c"`
	ContentD string `json:"content_d"`
	ContentE string `json:"content_e"`
	ContentF string `json:"content_f"`
	ContentG string `json:"content_g"`
	ContentH string `json:"content_h"`
	ContentI string `json:"content_i"`
	ContentJ string `json:"content_j"`
	ContentK string `json:"content_k"`
	ContentL string `json:"content_l"`
}

func BenchmarkSprintf(b *testing.B) {
	num := 10
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		fmt.Sprintf("%d", num)
	}
}
func BenchmarkFor(b *testing.B) {
	b.ReportAllocs()
	var a A = A{"aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee", "fffff", "gggggg", "hhhhhhhhhhhhh", "iiiiiiiiii", "jjjjjjjjjjj", "kkkkkkkkkkkk", "lllllllllll"}
	var bb B
	for i := 0; i < b.N; i++ {
		bb.ContentA = a.ContentA
		bb.ContentB = a.ContentB
		bb.ContentC = a.ContentC
		bb.ContentD = a.ContentD
		bb.ContentE = a.ContentE
		bb.ContentF = a.ContentF
		bb.ContentG = a.ContentG
		bb.ContentH = a.ContentH
		bb.ContentI = a.ContentI
		bb.ContentJ = a.ContentJ
		bb.ContentK = a.ContentK
		bb.ContentL = a.ContentL
	}
}

func BenchmarkJSON(b *testing.B) {
	b.ReportAllocs()
	var a A = A{"aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee", "fffff", "gggggg", "hhhhhhhhhhhhh", "iiiiiiiiii", "jjjjjjjjjjj", "kkkkkkkkkkkk", "lllllllllll"}
	var bb B
	for i := 0; i < b.N; i++ {
		body, _ := json.Marshal(&a)
		json.Unmarshal(body, &bb)
	}
}

2、go mod init bench
3、go test -bench=. -run=none
4、可以看出marshal确实比较耗费cpu.
Go入门笔记38-Go Benchmark

上一篇:Benchmark的一些心得


下一篇:Benchmark分析1:Cortexsuite.svd3