17

计算斐波那契数列的性能对比:Python,Java,Go

 4 years ago
source link: https://studygolang.com/articles/25677
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

  本文采用递归办法来计算斐波那契数列中的第38项,用于对于三种计算机语言的计算性能,这三种语言为:Python,Java,Go。

  我们采用递归法来求解斐波那契数列的第n项f(n),其算法描述如下:

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

对于公平起见,我们利用三种程序计算f(38),运行100遍,得到平均耗时,作为性能对比。

  Python程序如下:

# -*- 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程序如下:

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语言如下:

// 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)
}

  在同一台电脑上运行,得到的结果如下:

平均耗时(单位:秒) Python Java Go / 16.0151 0.1631 0.2398

可以看到,Java在该程序的性能表现最好,Go语言的效率比Python稍慢一些,但是是同一数量级,Python的运行时间大约是Go语言的66.7倍。

  本次分享到此结束,感谢大家的阅读~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK