erlang&c&python&lua递归执行效率

本文探讨了Erlang、C、Python和Lua这四种编程语言在实现递归算法时的执行效率差异。通过一系列基准测试,展示了不同语言在处理递归操作时的性能特点,揭示了它们各自的优势和适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

cpu_intensive.lua
function fib(n)
if n == 0 or n == 1 then
return 1
end
return fib(n-1) + fib(n-2)
end

fib(40)
fib(40)
fib(40)
fib(40)
n = fib(40)
print(n)


cpu_intensive.erl
-module(cpu_intensive). 
-compile(export_all). 

fib_test() -> 
fib(40), fib(40), fib(40), fib(40), fib(40). 

fib(0) -> 1; 
fib(1) -> 1; 
fib(N) -> fib(N-1) + fib(N-2). 


cpu_intensive.py
def fib(n):
    if n == 0 or n == 1:
        return 1
    return fib(n-1) + fib(n-2)

fib(40)
fib(40)
fib(40)
fib(40)
n = fib(40)
print(n)

cpu_intensive.cpp
#include "stdafx.h"
#include <stdio.h>

unsigned int fib(unsigned int n) { 
if (n == 0 || n == 1) { 
return 1; 
return fib(n-1) + fib(n-2); 

int _tmain(int argc, _TCHAR* argv[])
{
fib(40); fib(40); fib(40); fib(40); 
unsigned int n = fib(40); 
printf("%u", n);
return 0;
}

执行结果:
debug c 45s
release c <2s
erlang 53s
python 4min:18s
pypy 1min:8s
lua 2min:20s


另外有个10亿次数字相加的测试如下:

cputest2.erl
-module(cputest2).
-compile(export_all). 

test() ->
add(0).

add(N)
when N > 1000000000 ->
0;
add(N) ->
add(N+1).


cputest2.py
i = 0
while i < 1000000000:
    i = i + 1
print(i)


cputest2.lua
i = 0
while i < 1000000000 do
    i = i + 1
end
print(i)


cputest2.cpp
#include "stdafx.h"
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;
while(i < 1000000000)
i = i + 1;
printf("%d", i);

return 0;
}



执行结果:
python 90s
pypy 13s
erlang 55s
lua 65s
debug c 5s
release c <1s

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值