go channle 接收数据性能低下

以下是测试源码

  • select channle 使用在大数据量go程同步时 要慎用
  • 可以考虑锁sync.Mutex
  • 硬要使用channel 尽量将数据合并再发送
type t_chbuf chan interface{}

func sendToChBuf(ch_buf t_chbuf) {
    t1 := time.Now()
    for i := 0; i < 1000; i++ {

        ch_buf <- " [ROLE]" + strconv.Itoa(i) + ";"
    }
    elapsed := time.Since(t1)
    fmt.Println("SEND runtime:", elapsed)
}

func recvChBuf(ch_buf t_chbuf) {
    t1 := time.Now()

    rn := 0
    for {

        select {
        case num, _ := <-ch_buf:

            val, _ := num.(string)

            fmt.Println("RECV channel:", val, " len:", len(ch_buf))

            rn++
            if rn == 1000 {
                elapsed := time.Since(t1)
                fmt.Println("runtime:", elapsed, " COUNT:", rn)

            }
            //default:
            //  fmt.Println("DEFAULT NOTHING RECV")
            //  if rn == 1000 {
            //      //goto EXIT
            //  }
        }
    }
    //EXIT:
    elapsed := time.Since(t1)
    fmt.Println("runtime:", elapsed, " COUNT:", rn)
}

func main() {

    var ch_buf = make(t_chbuf, 1000)
    go sendToChBuf(ch_buf)
    go recvChBuf(ch_buf)

    time.Sleep(30 * time.Second)
}

1000 次发送耗时

RECV channel: [ROLE]0; len: 658
RECV channel: [ROLE]1; len: 998
RECV channel: [ROLE]2; len: 997
SEND runtime: 154.092µs

测试1000 次收结果以及执行时间

RECV channel: [ROLE]995; len: 4
RECV channel: [ROLE]996; len: 3
RECV channel: [ROLE]997; len: 2
RECV channel: [ROLE]998; len: 1
RECV channel: [ROLE]999; len: 0
runtime: 5.071627ms COUNT: 1000

共 2 个回复


me@bzza.com

没发现问题:
SEND runtime: 178.504µs
RECV channel: [ROLE]999; len: 0
runtime: 159.668µs COUNT: 1000

你那个问题是因为你fmt不断打印导致,去掉连续不断fmt即可!

# 0

slclub

嗯,有关系。 主要这个东西跑的非常稳

# 1