遞歸與循環的開銷比較,高精度時間函數

#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微秒,後者微妙級別以下。可見遞歸開銷很大。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章