在同一个目录下创建文件heapsort_test.go和heapsort.go
heapsort.go
package test import ( "log" "time" ) func main(){ // var a = []int{45,145,245,32,5,2,69,239,12,40} // log.Print("before: ", a) start := time.Now().UnixNano() heapsort(b) end := time.Now().UnixNano() log.Print("after: ", b) Milliseconds:= float64((end - start) / 1e6) log.Print("start_time, end_time, cost: ", start, end, Milliseconds) } func heapsort(arr []int) { len := len(arr) buildMaxHeap(arr) swap(arr, 0, len-1) for i := len-1;i>0;i-- { heapify(arr[0:i], 1) swap(arr[0:i], 0, i-1) } } func buildMaxHeap(arr []int) { lenH := len(arr) for i:=lenH/2;i>0;i-- { heapify(arr,i) } } func swap(arr []int, i int, j int) { temp := arr[i] arr[i] = arr[j] arr[j] = temp } /* * 指定位置的节点按最大堆调整 * */ func heapify(arr []int, heap int) { if (heap>len(arr) || heap*2>len(arr)){ return } // 比较左子节点 if (arr[heap-1] < arr[2*heap-1]) { swap(arr, heap-1, 2*heap-1) } // 比较右子节点 if (heap*2+1>len(arr)) { return } if (arr[heap-1] < arr[2*heap]) { swap(arr, heap-1, 2*heap) } // 子节点 heapify(arr, 2*heap) heapify(arr, 2*heap+1) }
heapsort_test.go
package test import ( "testing" ) var a = []int{45,145,245,32,5,2,69,239,12,40} func Benchmark_heapsort(b *testing.B) { for i:=0; i < b.N;i++{ buildMaxHeap(a) } }
在终端执行命令:
go test -bench . -count=2
显示:
含义:
- Benchmark_heapsort-8 中的 8 即
GOMAXPROCS
,默认等于 CPU 核数
-
17031591 88.43 ns/op
表示单位时间内(默认是1s)被测函数运行了 17031591 次,每次运行耗时 88.43ns,17031591*88.43ns=1.506s(耗时比 1s 略多,因为测试用例执行、销毁等是需要时间的)
- ok github.com/... 3.197s 表示总耗时3.197s