遞迴函式呼叫的代價
執行一下這個程式即可看出來。num的值不要設定太大。
遞迴函式大概是一般函式呼叫的2.5倍,是不用函式的8倍。
#include <iostream>
#include <ctime>
int x=0;
using namespace std;
long long sum=0;
void dizeng(int i)
{
if(i==0)return;
else
{
x++;
dizeng(i-1);
dizeng(i-1);
}
}
void jia(int i)
{
i++;
}
int main()
{
int t=clock();
int s=0;
int num=30;
dizeng(num);
printf("the number of run:%d/n",x);
int t2=clock();
printf("time of digui:%lf/n",(double(t2-t))/1000);
t=clock();
for(int i=1;i<x;i++)
jia(i);
t2=clock();
printf("time of yibanhanshu:%lf/n",(double(t2-t))/1000);
t=clock();
int y=0;
while(y<x)
{
y++;}
t2=clock();
printf("time of zhijiesuan:%lf/n",(double(t2-t))/1000);
system("pause");
}