The test way

Compare C and GO how do you deal with Fibonacci numbers

The test environment

  • CPU information:
CPU (Intel)Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz Number of cores 12 CPU Default frequency 2201 MHz CPU External frequency 100 MHz CPU Current frequency 2200 MHz Level-2 cache 1536 KB Level 3 cache 9216 KBCopy the code
  • tool
C Build tool: GCC version 8.1.0 (x86_64-POSIX-sjlJ-rev0, Built by MinGw-w64 Project) Go Version: Go Version GO1.13.6 Windows/AMD64Copy the code

Contrast test

The c language

  • The source code
// fib.c
#include <stdint.h>
#include <stdio.h>
#include <time.h>

static uint64_t fib(uint64_t n)
{
    if (n <= 1)
        return 1;
    return fib(n - 1) + fib(n - 2);
}

int main(void)
{
    time_t start, end;
    double cost;
    time(&start);
    printf("%llu \n", fib(46));
    time(&end);
    cost = difftime(end, start);
    printf("%fs", cost);

    return 0;
}
Copy the code
  • The results of
$GCC -o fibc fib.c $./fibc.exe 2971215073 9.000000s $./fibc.exe 2971215073 9.000000 S $./fibc.exe 2971215073 9.000000 S $ 9.000000 sCopy the code

The go

  • The source code
// fib.go
package main

import (
	"fmt"
	"time"
)

func fib(n uint64) uint64 {
	if n <= 1 {
		return 1
	}
	return fib(n- 1) + fib(n2 -)}func main(a) {
	start := time.Now()
	fmt.Printf("%v\n", fib(46))
	fmt.Println(time.Now().Sub(start))
}
Copy the code
  • The results of
$ go run "f:\Code\fib-test\fib.go"2971215073 9.648023s $go run"f:\Code\fib-test\fib.go"2971215073 9.6969298s $go run"f:\Code\fib-test\fib.go"2971215073 9.6968697 sCopy the code

conclusion

Comparison analysis shows that c is indeed faster to handle the same logic. However, the above is just a set of test data provided. In fact, in the process of testing, there were even fewer go times (for fear of being hit in the face, I did not post 😓), the reason is unknown. Depending on the operating environment of the current system, the measured value is different each time. A better way to handle this is to write a special test image using Docker. Recursive Fibonacci Benchmark using top Languages on Github is recommended. However, based on his data, MY C wasn’t that fast, and my GO wasn’t that slow. I hope that those who understand this way can give me some answers after seeing it. I really appreciate it.