goroutine切换效率测试

package main

import (
    "fmt"
    "os"
    "runtime"
    "time"
    "strconv"
)

const COUNT = 1000000
var i int = 0

func test() {
    for {
        i++
        if i > COUNT {
            break
        }

        runtime.Gosched()
    }
}

func main() {
    cpu_bind_num := 1

    if len(os.Args) > 1 {
        cpu_bind_num, _ = strconv.Atoi(os.Args[1])
    }

    runtime.GOMAXPROCS(cpu_bind_num)
    fmt.Printf("CPU %d ", cpu_bind_num)

    tv1 := time.Now().UnixNano()

    go test()

    // in main goroutine
    test()

    tv2 := time.Now().UnixNano()
    usetime := (tv2 - tv1) / 1000000

    fmt.Printf(" %d ms \n", usetime)
}

测试脚本:

cat test.sh
#!/bin/bash

for (( i=1; i <=8; i++ ))
do
    go run main.go $i
done

测试结果:

CPU 1  117 ms
CPU 2  213 ms
CPU 3  204 ms
CPU 4  203 ms
CPU 5  200 ms
CPU 6  205 ms
CPU 7  198 ms
CPU 8  203 ms

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注