github.com/zebozhuang/go@v0.0.0-20200207033046-f8a98f6f5c5d/src/context/benchmark_test.go (about) 1 // Copyright 2014 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package context_test 6 7 import ( 8 . "context" 9 "fmt" 10 "testing" 11 ) 12 13 func BenchmarkContextCancelTree(b *testing.B) { 14 depths := []int{1, 10, 100, 1000} 15 for _, d := range depths { 16 b.Run(fmt.Sprintf("depth=%d", d), func(b *testing.B) { 17 b.Run("Root=Background", func(b *testing.B) { 18 for i := 0; i < b.N; i++ { 19 buildContextTree(Background(), d) 20 } 21 }) 22 b.Run("Root=OpenCanceler", func(b *testing.B) { 23 for i := 0; i < b.N; i++ { 24 ctx, cancel := WithCancel(Background()) 25 buildContextTree(ctx, d) 26 cancel() 27 } 28 }) 29 b.Run("Root=ClosedCanceler", func(b *testing.B) { 30 for i := 0; i < b.N; i++ { 31 ctx, cancel := WithCancel(Background()) 32 cancel() 33 buildContextTree(ctx, d) 34 } 35 }) 36 }) 37 } 38 } 39 40 func buildContextTree(root Context, depth int) { 41 for d := 0; d < depth; d++ { 42 root, _ = WithCancel(root) 43 } 44 }