C++/Go/Lua 效率对比——函数调用

2019-07-18  本文已影响0人  loki528

测试递归函数调用——斐波那契数列
f(n) = f(n-1) + f(n-2)
f(1) = 1, f(2) = 1
计算f(40)
以C++效率作为参考

1.cpp

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
unsigned long long fib(unsigned int length)
{
    if (length <= 2)
        return 1;
    else
        return fib(length - 1) + fib(length -2);
}
class CalcTime
{
    public:
        CalcTime()
        {
            m_start = clock();
        }
        ~CalcTime()
        {
            unsigned long long end = clock();
            printf("cost time = %f\n", ((double)(end - m_start))/CLOCKS_PER_SEC);
        }
    private:
        unsigned long long m_start = 0;
};
int main(int argc, char** argv)
{
    printf("CLOCKS_PER_SEC = %d\n", CLOCKS_PER_SEC);
    if (argc < 2)
    {
        printf("Usage ./test 10\n");
        return -1;
    }
    unsigned int length = (unsigned int)atoi(argv[1]);
    printf("length = %u\n", length);
    {
        CalcTime calc;
        printf("sum = %lu", fib(length));
    }
    return 0;
}

cost time = 0.240000

2.Go

test_go.go

package main
import "time"
import "fmt"
func fib(len uint) uint {
    if len < 2 {
        return 1
    } else {
        return fib(len-1) + fib(len-2)
    }
}
func main() {
    start := time.Now()
    fib(40)
    end := time.Now()
    dif := end.Sub(start)
    fmt.Printf("cost time: %v\n", dif)
}

cost time: 787.068158ms
cost time: 778.367689ms
cost time: 771.180767ms
cost time: 772.44155ms
cost time: 773.12639ms
平均时间=776.44ms

3. lua

#!/usr/bin/lua
require("os")
function fib(n)
    if n <= 2 then
        return 1
    else
        return fib(n -1) + fib(n - 2)
    end
end
local starttime = os.clock()
local length = 40
print("sum = ", fib(length))
local endtime = os.clock()
print(string.format("cost time : %.4f", endtime - starttime))

cost time : 12.0500
cost time : 11.1700
cost time : 11.9500
cost time : 12.3200
cost time : 11.7700
平均时间=11.852s

总结:

函数调用耗时对比
C++ /Go/Lua
240 : 776.44 : 11852
1: 3.235: 49.383

上一篇 下一篇

猜你喜欢

热点阅读