Golang Notes

测试

Test 代码测试

func TestAdd(t *testing.T) {
    tests := []struct{a, b, c int}{
        {1, 2, 3},
        {4, 5, 6},
        {123, 345, 468},
        {1, 345, 468},
    }

    for _, tt :=range tests{
        if actual := add(tt.a, tt.b); actual!=tt.c{
            t.Errorf("add(%d, %d); get %d; expected %d\n", tt.a, tt.b, actual, tt.c)
        }
    }
}

Benchmark 性能测试

性能数据分析

测试代码

func BenchmarkAdd(b *testing.B){

    inA, inB:=123, 345
    outC:=468

    // 之前操作不计入计时
    b.ResetTimer()
    for i:=0;i<b.N;i++ {
        actual := add(inA, inB)
        if actual != outC {
            b.Errorf("add(%d, %d); get %d; expected %d\n", 
                inA, inB, actual, outC)
        }
    }
}

命令行操作

// 运行测试
go test -bench . -cpuprofile cpu.out

// 分析输出的测试数据文件`cpu.out`
go tool pprof cpu.out

// 交互页面输入web生成svg分析数据
// 需要下载工具并配置环境变量

工具 Graphviz - Graph Visualization Software

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容