GOMAXPROCS でマルチコアCPUを有効に使う

via

#golang でマルチコアをつかいきれた人っているの?

http://twitter.com/tokuhirom/status/6229784117

# 何か、以下のような意味じゃない気もするんだけどとりあえず

お互いに無関係な (フィボナッチ数を求める) goroutine を 3つ走らせて、それに対して環境変数 GOMAXPROCS を 1〜5 まで変えたらどうなったか、の結果です。

Linux 2.6.31-15-generic #50-Ubuntu SMP Tue Nov 10 14:53:52 UTC 2009 x86_64 unknown GNU/Linux
GOMAXPROCS=1 ./6.out  3.83s user 0.01s system 99% cpu 3.842 total
GOMAXPROCS=2 ./6.out  3.39s user 0.01s system 143% cpu 2.371 total
GOMAXPROCS=3 ./6.out  3.21s user 0.00s system 187% cpu 1.712 total
GOMAXPROCS=4 ./6.out  3.33s user 0.00s system 181% cpu 1.838 total
GOMAXPROCS=5 ./6.out  3.36s user 0.01s system 188% cpu 1.789 total
Darwin 10.2.0 Darwin Kernel Version 10.2.0: Tue Nov  3 10:37:10 PST 2009; root:xnu-1486.2.11~1/RELEASE_I386 i386 i386
GOMAXPROCS=1 ./8.out  7.25s user 0.01s system 99% cpu 7.302 total
GOMAXPROCS=2 ./8.out  7.25s user 0.02s system 136% cpu 5.325 total
GOMAXPROCS=3 ./8.out  7.31s user 0.02s system 182% cpu 4.013 total
GOMAXPROCS=4 ./8.out  7.39s user 0.02s system 164% cpu 4.494 total
GOMAXPROCS=5 ./8.out  7.42s user 0.02s system 180% cpu 4.131 total

どちらも dual core のマシンなのですが、GOMAXPROCS=3 以上で二つのコアをちゃんと使えているようではあります。quad core (で Go が動かせる) マシンが今手元にないので、quad だとどうなるかは興味のあるところ。

実行したソースコードは以下です。

package main
func fib (n int) int {
    if n <= 2 { return n };
    return fib(n - 2) + fib(n - 1);
}
func main () {
    n  := 40;
    ch := make(chan int);
    for i := 0; i < 3; i++ {
        go func() { ch <- fib(n) }();
    }
    for i := 0; i < 3; i++ {
        <-ch;
    }
}