8-2 代码覆盖率和性能测试

 

go test

代码覆盖率:

go test -coverprofile=c.out 

go tool cover -html=c.out // 通过html查看

go tool cover // 查看cover帮助

go test -coverprofile=c.out -v nonrepeating_test.go // 指定某个_test.go文件

性能测试:

go test -bench .

代码:https://github.com/NIGHTFIGHTING/go_learning/blob/master/src/basic/nonrepeating/nonrepeating_test.go

package main

import (
    "testing"
)
func lengthOfNonRepeatingSubStr(s string) int {
    //lastOccurred := make(map[byte]int)
    lastOccurred := make(map[rune]int)
    start := 0
    maxLength := 0

    //for i, ch := range []byte(s) {
    for i, ch := range []rune(s) {
        if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
            start = lastOccurred[ch] + 1
        }
        if i-start+1 > maxLength {
            maxLength = i - start + 1
        }
        lastOccurred[ch] = i
    }
    return maxLength
}
func TestSubstr(t *testing.T) {
    tests := []struct {
        s string
        ans int
    } {
        // Normal cases
        {"abcabcbb", 3},
        {"pwwkew", 3},
        // Edge cases
        {"", 0},
        {"b", 1},
        {"bbbbbbbb", 1},
        {"abcabcabcd", 4},
        // Chinense cases
        {"这里是慕课网", 6},
        {"一二三二一", 3},
        {"黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花", 8},
    }

    for _, tt := range tests {
        actual := lengthOfNonRepeatingSubStr(tt.s)
        if actual != tt.ans {
            t.Errorf("got %d for input %s; " +
                "expected %d",
                actual, tt.s, tt.ans)
        }
    }
}

func BenchmarkSubstr(b *testing.B) {
    s := "黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花"
    ans := 8
    for i := 0; i < b.N; i++ {
        actual := lengthOfNonRepeatingSubStr(s)
        if actual != ans {
            b.Errorf("got %d for input %s; " +
                "expected %d",
                actual, s, ans)
        }
    }
}

 

其中b.N的值系统会帮我们设定

性能测试:go test -bench .

说明每次操作花了1194ns的时间,总共执行了1000000次。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值