funcBenchmark_Push(b *testing.B) { for i := 0; i < b.N; i++ { //use b.N for looping now := strconv.Itoa(i) stack.Push("test" + now) }
//fmt.Println(stack) }
funcBenchmark_Pop(b *testing.B) { b.StopTimer() //类似时间锁,在StopTimer()和StartTimer()之见的代码,不计入测量 for i := 0; i < b.N; i++ { //use b.N for looping now := strconv.Itoa(i) stack.Push("test" + now) } b.StartTimer() for i := 0; i < b.N; i++ { //use b.N for looping stack.Pop() } }
funcBenchmark_Push(b *testing.B) { for i := 0; i < b.N; i++ { //use b.N for looping now := strconv.Itoa(i) stack.Push("test" + now) }
//fmt.Println(stack) }
funcBenchmark_Pop(b *testing.B) { b.StopTimer() //类似时间锁,在StopTimer()和StartTimer()之见的代码,不计入测量 for i := 0; i < b.N; i++ { //use b.N for looping now := strconv.Itoa(i) stack.Push("test" + now) } b.StartTimer() for i := 0; i < b.N; i++ { //use b.N for looping stack.Pop() } }
type ( Stack struct { top *node length int lock *sync.RWMutex } node struct { value interface{} prev *node } )
// Create a new stack funcNewStack() *Stack { return &Stack{nil, 0, &sync.RWMutex{}} }
// Return the number of items in the stack func(this *Stack) Len() int { return this.length }
// View the top item on the stack func(this *Stack) Peek() interface{} { if this.length == 0 { returnnil } return this.top.value }
// Pop the top item of the stack and return it func(this *Stack) Pop() interface{} { this.lock.Lock() defer this.lock.Unlock() if this.length == 0 { returnnil } n := this.top this.top = n.prev this.length-- return n.value }
// Push a value onto the top of the stack func(this *Stack) Push(value interface{}) { this.lock.Lock() defer this.lock.Unlock() n := &node{value, this.top} this.top = n this.length++ }