github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bench/chan/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  
     7  	"github.com/loov/hrtime"
     8  )
     9  
    10  func main() {
    11  	const P = 4
    12  	const K = 100
    13  	const N = 1000000
    14  
    15  	{
    16  		bench := hrtime.NewBenchmarkTSC(K)
    17  		for bench.Next() {
    18  			_ = make(chan int, N)
    19  		}
    20  		hist := bench.Histogram(10)
    21  		hist.Divide(N)
    22  		fmt.Println("make\n", hist.StringStats())
    23  	}
    24  
    25  	{
    26  		bench := hrtime.NewBenchmarkTSC(K)
    27  		for bench.Next() {
    28  			ch := make(chan int, N)
    29  			for i := 0; i < N; i++ {
    30  				ch <- i
    31  			}
    32  		}
    33  		hist := bench.Histogram(10)
    34  		hist.Divide(N)
    35  		fmt.Println("uncontended send\n", hist.StringStats())
    36  	}
    37  
    38  	{
    39  		bench := hrtime.NewBenchmarkTSC(K)
    40  		for bench.Next() {
    41  			ch := make(chan int, N)
    42  			for i := 0; i < N; i++ {
    43  				ch <- i
    44  			}
    45  			for i := 0; i < N; i++ {
    46  				<-ch
    47  			}
    48  		}
    49  		hist := bench.Histogram(10)
    50  		hist.Divide(N)
    51  		fmt.Println("uncontended send/recv\n", hist.StringStats())
    52  	}
    53  
    54  	{
    55  		bench := hrtime.NewBenchmarkTSC(K)
    56  		for bench.Next() {
    57  			ch := make(chan int, N)
    58  			var wg sync.WaitGroup
    59  			wg.Add(P)
    60  			for k := 0; k < P; k++ {
    61  				go func() {
    62  					for i := 0; i < N/P; i++ {
    63  						ch <- i
    64  					}
    65  					wg.Done()
    66  				}()
    67  			}
    68  			wg.Wait()
    69  		}
    70  		hist := bench.Histogram(10)
    71  		hist.Divide(N)
    72  		fmt.Println("contended send\n", hist.StringStats())
    73  	}
    74  
    75  	{
    76  		bench := hrtime.NewBenchmarkTSC(K)
    77  		for bench.Next() {
    78  			ch := make(chan int, N)
    79  			var wg sync.WaitGroup
    80  
    81  			wg.Add(P)
    82  			for k := 0; k < P; k++ {
    83  				go func() {
    84  					for i := 0; i < N/P; i++ {
    85  						ch <- i
    86  					}
    87  					wg.Done()
    88  				}()
    89  			}
    90  			wg.Wait()
    91  
    92  			wg.Add(P)
    93  			for k := 0; k < P; k++ {
    94  				go func() {
    95  					for i := 0; i < N/P; i++ {
    96  						<-ch
    97  					}
    98  					wg.Done()
    99  				}()
   100  			}
   101  			wg.Wait()
   102  		}
   103  		hist := bench.Histogram(10)
   104  		hist.Divide(N)
   105  		fmt.Println("contended send/recv\n", hist.StringStats())
   106  	}
   107  }