• 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。
    image

    本博客是个人工作中记录,遇到问题可以互相探讨,没有遇到的问题可能没有时间去特意研究,勿扰。
    另外建了几个QQ技术群:
    2、全栈技术群:616945527,加群口令abc123
    2、硬件嵌入式开发: 75764412
    3、Go语言交流群:9924600

    闲置域名www.nsxz.com出售(等宽等高字符四字域名)。
  • 相关阅读:
    git简单使用
    简单Spring和mybatis整合配置文件
    ASP.NET程序开发范例宝典
    C# DataSet和DataTable详解
    AOP
    匿名内部类
    数据库事务
    mybatis
    线程池
    单例模式
  • 原文地址:https://www.cnblogs.com/zhaogaojian/p/15229241.html
Copyright © 2020-2023  润新知