【发布时间】:2014-11-26 21:02:42
【问题描述】:
我试图找出 Go 的循环性能是否与 C 一样好,但意外地发现,对于我的简单测试,C 版本的时间是 Go 版本的两倍。
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
Go 版本:
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 For go:“[Go] 编译器生成的代码默认是‘优化’的:” 来源:plan9.bell-labs.com/sys/doc/comp.pdf via golang.org/cmd/gc
-
您可以获取 asm 供两者进行比较(对于 Go,它类似于
go build -gcflags -S)。我很困惑,但是您的 Go 使用的是 32 位整数,而 C 可能使用的是 64,也许 64 位除法是一条慢得多的指令。或者 Go 在这里有一些优化,在 gcc 的默认优化级别上没有启用。 -
参考@delnan,see comparison of optimized vs. not here。
-
你为什么要比较不同的代码???您至少应该对两者使用相同的
for或while。
标签: c go benchmarking compiler-optimization computer-architecture