# Test

// twoSum 给定数组，求两个之和的数组内地址
func twoSum(nums []int, target int) []int {
hashTable := map[int]int{}
for i, x := range nums {
if p, ok := hashTable[target-x]; ok {
return []int{p, i}
}
hashTable[x] = i
}
return nil
}


package twoSum

import (
"testing"
)

func TestTwoSum(t *testing.T) {

}


func TestTwoSum(t *testing.T) {
args := []struct {
nums   []int
target int
source []int
}{
{[]int{2, 7, 11, 15}, 9, []int{0, 1}},
{[]int{2, 7, 11, 15}, 13, []int{0, 2}},
{[]int{0, 1, 0}, 0, []int{0, 2}},
}
for _, arg := range args {
sum := twoSum(arg.nums, arg.target)
for i, v := range sum {
if arg.source[i] != v {
fmt.Printf("nums:%v,target:%v,right:%v,source:%v", arg.nums, arg.target, sum, arg.source)
}
}
}
}


# 性能测试

func BenchmarkTwoSum(b *testing.B) {
nums := []int{2, 7, 11, 15, 24, 22, 44}
target := 9
source := []int{0, 1}
b.ResetTimer()
for i := 0; i < b.N; i++ {
sum := twoSum(nums, target)
for i, v := range sum {
if source[i] != v {
fmt.Printf("nums:%v,target:%v,right:%v,source:%v", nums, target, sum, source)
}
}
}
}


b.ResetTimer() // 数据准备完成，从这一行对性能进行统计

b.N		// 循环的次数由系统决定


go test -bench .


# 通过命令生成性能测试文件
go test -bench . -cpuprofile cpu.out
# 能过web方式查看性能文件
go tool pprof cpu.out
# 最后输入 web 后会自动弹出网页
web


posted @ 2022-04-06 00:34  一点浩然气~  阅读(530)  评论(0编辑  收藏  举报