...
Run Format

Source file src/context/benchmark_test.go

Documentation: context

     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  	"runtime"
    11  	"sync"
    12  	"testing"
    13  	"time"
    14  )
    15  
    16  func BenchmarkWithTimeout(b *testing.B) {
    17  	for concurrency := 40; concurrency <= 4e5; concurrency *= 100 {
    18  		name := fmt.Sprintf("concurrency=%d", concurrency)
    19  		b.Run(name, func(b *testing.B) {
    20  			benchmarkWithTimeout(b, concurrency)
    21  		})
    22  	}
    23  }
    24  
    25  func benchmarkWithTimeout(b *testing.B, concurrentContexts int) {
    26  	gomaxprocs := runtime.GOMAXPROCS(0)
    27  	perPContexts := concurrentContexts / gomaxprocs
    28  	root := Background()
    29  
    30  	// Generate concurrent contexts.
    31  	var wg sync.WaitGroup
    32  	ccf := make([][]CancelFunc, gomaxprocs)
    33  	for i := range ccf {
    34  		wg.Add(1)
    35  		go func(i int) {
    36  			defer wg.Done()
    37  			cf := make([]CancelFunc, perPContexts)
    38  			for j := range cf {
    39  				_, cf[j] = WithTimeout(root, time.Hour)
    40  			}
    41  			ccf[i] = cf
    42  		}(i)
    43  	}
    44  	wg.Wait()
    45  
    46  	b.ResetTimer()
    47  	b.RunParallel(func(pb *testing.PB) {
    48  		wcf := make([]CancelFunc, 10)
    49  		for pb.Next() {
    50  			for i := range wcf {
    51  				_, wcf[i] = WithTimeout(root, time.Hour)
    52  			}
    53  			for _, f := range wcf {
    54  				f()
    55  			}
    56  		}
    57  	})
    58  	b.StopTimer()
    59  
    60  	for _, cf := range ccf {
    61  		for _, f := range cf {
    62  			f()
    63  		}
    64  	}
    65  }
    66  
    67  func BenchmarkCancelTree(b *testing.B) {
    68  	depths := []int{1, 10, 100, 1000}
    69  	for _, d := range depths {
    70  		b.Run(fmt.Sprintf("depth=%d", d), func(b *testing.B) {
    71  			b.Run("Root=Background", func(b *testing.B) {
    72  				for i := 0; i < b.N; i++ {
    73  					buildContextTree(Background(), d)
    74  				}
    75  			})
    76  			b.Run("Root=OpenCanceler", func(b *testing.B) {
    77  				for i := 0; i < b.N; i++ {
    78  					ctx, cancel := WithCancel(Background())
    79  					buildContextTree(ctx, d)
    80  					cancel()
    81  				}
    82  			})
    83  			b.Run("Root=ClosedCanceler", func(b *testing.B) {
    84  				for i := 0; i < b.N; i++ {
    85  					ctx, cancel := WithCancel(Background())
    86  					cancel()
    87  					buildContextTree(ctx, d)
    88  				}
    89  			})
    90  		})
    91  	}
    92  }
    93  
    94  func buildContextTree(root Context, depth int) {
    95  	for d := 0; d < depth; d++ {
    96  		root, _ = WithCancel(root)
    97  	}
    98  }
    99  

View as plain text