语言运行速度的一次测试

做了一个实验,比较Python、C、Go的运行速度,结果居然是... ...

代码目标:计算斐波纳契数列

C代码:

int fib(int n){
   if (n < 2)
     return n;
   else
     return fib(n - 1) + fib(n - 2);
}

int main() {
    fib(40);
    return 0;
}

Go代码:

package main

func fib(n int) int {
    var r int
    if n < 2 {
        r = n
    } else {
        r = fib(n - 1) + fib(n - 2)
    }

    return r
}

func main(){
    fib(40)
}

Python代码:

def fib(n):
  if n < 2:
     return n
  else:
     return fib(n - 1) + fib(n - 2)
fib(40)

测试机CPU信息:

[liuxd@liuxd]$ [master] cat /proc/cpuinfo 
processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 23
model name  : Intel(R) Core(TM)2 Duo CPU     E8400  @ 3.00GHz
stepping    : 10
microcode   : 0xa0b
cpu MHz     : 1995.000
cache size  : 6144 KB
physical id : 0
siblings    : 2
core id     : 0
cpu cores   : 2
apicid      : 0
initial apicid  : 0
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good nopl aperfmperf pni dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm sse4_1 xsave lahf_lm dtherm tpr_shadow vnmi flexpriority
bogomips    : 5984.93
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

processor   : 1
vendor_id   : GenuineIntel
cpu family  : 6
model       : 23
model name  : Intel(R) Core(TM)2 Duo CPU     E8400  @ 3.00GHz
stepping    : 10
microcode   : 0xa0b
cpu MHz     : 2995.000
cache size  : 6144 KB
physical id : 0
siblings    : 2
core id     : 1
cpu cores   : 2
apicid      : 1
initial apicid  : 1
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good nopl aperfmperf pni dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm sse4_1 xsave lahf_lm dtherm tpr_shadow vnmi flexpriority
bogomips    : 5984.93
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

测试结果:
Python:

real    0m52.221s
user    0m51.999s
sys 0m0.025s

C:

real    0m2.260s
user    0m2.249s
sys 0m0.001s

Go:

real    0m1.534s
user    0m1.530s
sys 0m0.001s

我每种语言都跑过5次以上,运行时间误差在0.01秒以内。

Go比C还快?这是啥道理?

你可能感兴趣的:(c,python,Go)