为什么在goroutine的select中有一个默认子句会让它变慢?

时间:2018-06-03 11:34:03

标签: go

参考以下基准测试代码:

func BenchmarkRuneCountNoDefault(b *testing.B) {
    b.StopTimer()
    var strings []string
    numStrings := 10
    for n := 0; n < numStrings; n++{
        s := RandStringBytesMaskImprSrc(10)
        strings = append(strings, s)
    }
    jobs := make(chan string)
    results := make (chan int)

    for i := 0; i < runtime.NumCPU(); i++{
        go RuneCountNoDefault(jobs, results)
    }
    b.StartTimer()

    for n := 0; n < b.N; n++ {
        go func(){
            for n := 0; n < numStrings; n++{
                <-results
            }
            return
        }()

        for n := 0; n < numStrings; n++{
            jobs <- strings[n]
        }
    }

    close(jobs)
}

func RuneCountNoDefault(jobs chan string, results chan int){
    for{
        select{
        case j, ok := <-jobs:
            if ok{
                results <- utf8.RuneCountInString(j)
            } else {
                return
            }
        }
    }
}

func BenchmarkRuneCountWithDefault(b *testing.B) {
    b.StopTimer()
    var strings []string
    numStrings := 10
    for n := 0; n < numStrings; n++{
        s := RandStringBytesMaskImprSrc(10)
        strings = append(strings, s)
    }
    jobs := make(chan string)
    results := make (chan int)

    for i := 0; i < runtime.NumCPU(); i++{
        go RuneCountWithDefault(jobs, results)
    }
    b.StartTimer()

    for n := 0; n < b.N; n++ {
        go func(){
            for n := 0; n < numStrings; n++{
                <-results
            }
            return
        }()

        for n := 0; n < numStrings; n++{
            jobs <- strings[n]
        }
    }

    close(jobs)
}


func RuneCountWithDefault(jobs chan string, results chan int){
    for{
        select{
        case j, ok := <-jobs:
            if ok{
                results <- utf8.RuneCountInString(j)
            } else {
                return
            }
        default: //DIFFERENCE
        }
    }
}

//https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
    letterIdxBits = 6                    // 6 bits to represent a letter index
    letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
    letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
)

var src = rand.NewSource(time.Now().UnixNano())

func RandStringBytesMaskImprSrc(n int) string {
    b := make([]byte, n)
    // A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
    for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
        if remain == 0 {
            cache, remain = src.Int63(), letterIdxMax
        }
        if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
            b[i] = letterBytes[idx]
            i--
        }
        cache >>= letterIdxBits
        remain--
    }

    return string(b)
}

当我对RuneCountNoDefault中另一个函数default没有select子句的另一个函数进行基准测试时,RuneCountWithDefault有一个default子句,我得到以下基准:

BenchmarkRuneCountNoDefault-4             200000              8910 ns/op
BenchmarkRuneCountWithDefault-4                5         277798660 ns/op

检查测试生成的cpuprofile,我注意到带有default子句的函数在以下通道操作中花费了大量时间:

enter image description here

为什么在goroutine的select中有一个默认子句会让它变慢?

我正在使用Go版1.10进行windows/amd64

1 个答案:

答案 0 :(得分:6)

  

The Go Programming Language Specification

     

Select statements

     

如果一个或多个通信可以进行,则单个通信   可以通过统一的伪随机选择来选择。   否则,如果存在默认情况,则选择该情况。如果有   没有默认情况,“select”语句会阻塞至少一个   通讯可以继续。

修改您的基准以计算所采取的继续和默认案例的数量:

$ go test default_test.go -bench=.
goos: linux
goarch: amd64
BenchmarkRuneCountNoDefault-4         300000          4108 ns/op
BenchmarkRuneCountWithDefault-4           10     209890782 ns/op
--- BENCH: BenchmarkRuneCountWithDefault-4
    default_test.go:90: proceeds 114
    default_test.go:91: defaults 128343308
$ 

虽然其他情况无法继续,但默认情况下在209422470(209890782 - 114 * 4108)中采用128343308次,默认情况下为纳秒或1.63纳秒。如果你做了很多次小事,那就加起来了。

default_test.go

package main

import (
    "math/rand"
    "runtime"
    "sync/atomic"
    "testing"
    "time"
    "unicode/utf8"
)

func BenchmarkRuneCountNoDefault(b *testing.B) {
    b.StopTimer()
    var strings []string
    numStrings := 10
    for n := 0; n < numStrings; n++ {
        s := RandStringBytesMaskImprSrc(10)
        strings = append(strings, s)
    }
    jobs := make(chan string)
    results := make(chan int)

    for i := 0; i < runtime.NumCPU(); i++ {
        go RuneCountNoDefault(jobs, results)
    }
    b.StartTimer()

    for n := 0; n < b.N; n++ {
        go func() {
            for n := 0; n < numStrings; n++ {
                <-results
            }
            return
        }()

        for n := 0; n < numStrings; n++ {
            jobs <- strings[n]
        }
    }

    close(jobs)
}

func RuneCountNoDefault(jobs chan string, results chan int) {
    for {
        select {
        case j, ok := <-jobs:
            if ok {
                results <- utf8.RuneCountInString(j)
            } else {
                return
            }
        }
    }
}

var proceeds ,defaults uint64

func BenchmarkRuneCountWithDefault(b *testing.B) {
    b.StopTimer()
    var strings []string
    numStrings := 10
    for n := 0; n < numStrings; n++ {
        s := RandStringBytesMaskImprSrc(10)
        strings = append(strings, s)
    }
    jobs := make(chan string)
    results := make(chan int)

    for i := 0; i < runtime.NumCPU(); i++ {
        go RuneCountWithDefault(jobs, results)
    }
    b.StartTimer()

    for n := 0; n < b.N; n++ {
        go func() {
            for n := 0; n < numStrings; n++ {
                <-results
            }
            return
        }()

        for n := 0; n < numStrings; n++ {
            jobs <- strings[n]
        }
    }

    close(jobs)

    b.Log("proceeds", atomic.LoadUint64(&proceeds))
    b.Log("defaults", atomic.LoadUint64(&defaults))

}

func RuneCountWithDefault(jobs chan string, results chan int) {
    for {
        select {
        case j, ok := <-jobs:

            atomic.AddUint64(&proceeds, 1)

            if ok {
                results <- utf8.RuneCountInString(j)
            } else {
                return
            }
        default: //DIFFERENCE

            atomic.AddUint64(&defaults, 1)

        }
    }
}

//https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
    letterIdxBits = 6                    // 6 bits to represent a letter index
    letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
    letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
)

var src = rand.NewSource(time.Now().UnixNano())

func RandStringBytesMaskImprSrc(n int) string {
    b := make([]byte, n)
    // A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
    for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
        if remain == 0 {
            cache, remain = src.Int63(), letterIdxMax
        }
        if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
            b[i] = letterBytes[idx]
            i--
        }
        cache >>= letterIdxBits
        remain--
    }

    return string(b)
}

游乐场:https://play.golang.org/p/DLnAY0hovQG