我試圖找出Go的循環性能是否與C一樣好,但是令人驚訝的是,對於我的簡單測試,C版本花費兩倍於Go版本的時間。爲什麼Go中的這個簡單循環比C中的更快?
C版:
#include <stdio.h>
int main() {
int i = 0, a = 0;
while (i < 1e9) {
a = (a + i) % 42;
i = i + 1;
}
printf("%d\n", a);
}
,
$ gcc -o main main.c && time ./main # tried -O0 as well; the result is similar
36
./main 10.53s user 0.08s system 98% cpu 10.769 total
轉到版本:
package main
import "fmt"
func main() {
a := int32(0)
for i := int32(0); i < 1e9; i++ {
a = (a + i) % 42
}
fmt.Println(a)
}
,
$ time go run main.go
36
colorgo run main.go 5.27s user 0.14s system 93% cpu 5.816 total
(在達爾文測試,amd64)
對於這個簡單的算法,不應該他們都產生幾乎相同的機器碼?這是由於編譯器優化?緩存效率?
請幫我理解!謝謝!
你的C程序編譯時沒有任何優化。 Go編譯器可能會有一個不同的默認值,並且不經過指示即可進行優化。用'gcc -O2'編譯一個更公平的比較。 – delnan 2014-10-01 21:51:07
@delnan For go:「由[Go]編譯器生成的代碼默認爲'優化':」source:http://plan9.bell-labs.com/sys/doc/comp.pdf通過http:// golang.org/cmd/gc/ – dyp 2014-10-01 21:54:12
你可以得到asm來進行比較(對於Go就像'go build -gcflags -S')。我很困難,但你的Go使用的是32位整數,而C可能使用64,而64位除法是一個非常慢的指令。那或者Go在這裏有一些不在gcc的默認優化級別上的優化。 – twotwotwo 2014-10-01 21:55:07