#include <iostream>
using namespace std;
#include <sys/time.h>
long p(long n);
int main()
{
struct timeval start, end;
gettimeofday(&start, NULL);
cout<<p(10)<<endl;
gettimeofday(&end, NULL);
long seconds = end.tv_sec - start.tv_sec;
long useconds = end.tv_usec - start.tv_usec;
long elapsed = seconds*1000*1000 + useconds ;
cout<<elapsed;
return 0;
}
long p(long n){
if (n==1) return 1;
else return n*p(n-1);
}
遞歸方法實現階乘。
結果:
3628800
83
------------------
(program exited with code: 0)
Press return to continue
====================================================================
#include <iostream>
using namespace std;
#include <sys/time.h>
int main()
{
long i,n=10;
long sum=1;
struct timeval start, end;
gettimeofday(&start, NULL);
for(i=1;i<=n;i++){sum*=i;}
gettimeofday(&end, NULL);
cout<<sum<<endl;
long seconds = end.tv_sec - start.tv_sec;
long useconds = end.tv_usec - start.tv_usec;
long elapsed = seconds*1000*1000 + useconds ;
cout<<elapsed;
return 0;
}
循環實現階乘。
結果:
3628800
0
------------------
(program exited with code: 0)
Press return to continue
=================================================================
前者耗時83微秒,後者微妙級別以下。可見遞歸開銷很大。