## That performance comparison of Number of computing Fibonacci: Python, Java, Go

In this paper, the recursive approach to compute Fibonacci first 38 contract number column for the calculation of the performance of three kinds of computer languages, three languages is: Python, Java, Go.
We use Fibonacci recursion to solve the first n items f (n) of Number, the algorithm is described as follows:

``````function fib(n)
if n = 0 return 0
if n = 1 return 1
return fib(n − 1) + fib(n − 2)``````

For fairness, we use three types of procedures calculated f (38), running 100 times, an average time-consuming, as a performance comparison.

Python program is as follows:

``````# -*- coding: utf-8 -*-
# author: Jclian91
# place: Pudong Shanghai
# time: 16:15

import time

# recursive method
def rec_fib(n):
if n <= 1:
return n
else:
return rec_fib(n-1) + rec_fib(n-2)

time_cost = 0
for _ in range(100):
# time cost of cursive method
t1 = time.time()
t = rec_fib(38)
t2 = time.time()
time_cost += (t2-t1)

print('结果：%s, 平均运行时间：%s'%(t, time_cost/100))``````

Java programs are as follows:

``````import java.util.Date;

public class Main {

// 主函数
public static void main(String[] args) {
double time_cost = 0;
for (int i=0; i<100; i++) {
Date start_time = new Date(); //开始时间
int n = 38;
rec_fib(n);
Date end_time1 = new Date(); // 结束时间
Long cost_time1 = end_time1.getTime() - start_time.getTime();  // 计算时间，返回毫秒数
time_cost += cost_time1;
}
System.out.println(String.format("Average cost time is %.3fs.", time_cost*1.0/1000));
}

// 利用递归方法计算斐波那契数列的第n项
public static int rec_fib(int n){
if(n == 0)
return 0;
if(n ==1)
return 1;
else
return rec_fib(n-1) + rec_fib(n-2);
}

}``````

Go language as follows:

``````// rec_fib
package main

import (
"fmt"
"time"
)

// 函数返回第n个斐波那契数
func rec_fib(num int) int {
if num <= 1 {
return num
} else {
return rec_fib(num-1) + rec_fib(num-2)
}
}

func main() {
var time_cost float64
for i := 0; i < 100; i++ {
t1 := time.Now()
n := 38
rec_fib(n)
t2 := time.Now()
time_cost += t2.Sub(t1).Seconds()
}
fmt.Printf("Average cost time: %f.\n", time_cost/100)
}``````

Running on the same computer, the results are as follows:

Average duration (unit: seconds) Python Java Go
/ 16.0151 0.1631 0.2398

You can see, Java best efficiency than the Python language Go slower in performance of the program, but is of the same order of magnitude, Python's run time is about 66.7 times the Go language.

The share is over, thanks for reading ~

### Guess you like

Origin www.cnblogs.com/jclian91/p/12113154.html
Recommended
Ranking
Daily