B-樹 實現3

    上次有了B-樹的兩種不同的實現,現在我們來測試一下兩種實現的效率,由於命名一樣,我設置了不同的名字空間,下面是測試代碼:

#include <iostream>
#include <string>
#include <cmath>
#include <ctime>
#include "BTree.h"
#include "BTree2.h"

using namespace std;
const int maxcnt = 1000000;
int r[maxcnt];
int order[maxcnt];

int main()
{
	
	int i;
	clock_t start,finish;
	double totaltime;

	srand( time(NULL) );
	for ( i = 0; i < maxcnt; ++ i )
		r[i] = rand();

	namespace2::BTree<int, int, 6> tree2;
	BTree<int, int, 3> tree;

	cout << "test insertion..." << endl;
	start = clock();
	for ( i = 0; i < maxcnt; ++ i )
		tree.Insert( r[i], r[i] );
	finish = clock();
	cout << "算法導論: " << (double)(finish-start)/CLOCKS_PER_SEC << "  " << "split count: " << tree.SplitCnt << endl;

	start = clock();
	for ( i = 0; i < maxcnt; ++ i )
		tree2.Insert( r[i], r[i] );
	finish = clock();
	cout << "回溯版本: " << (double)(finish-start)/CLOCKS_PER_SEC << "  " << "split count: " << tree2.SplitCnt << endl;

	cout << "test deletion..." << endl;
	
	srand( time(NULL) );
	for ( i = 0; i < maxcnt; ++ i )
		order[i] = rand()%maxcnt;

	start = clock();
	for ( i = 0; i < maxcnt; ++ i )
		tree.Delete( r[ order[i] ] ); 
	finish = clock();
	cout << "算法導論: " << (double)(finish-start)/CLOCKS_PER_SEC << "  " << "merge count: " << tree.MergeCnt 
		<< " from key: " << tree.FromCnt << " total cnt: " << tree.MergeCnt+tree.FromCnt << endl;

	start = clock();
	for ( i = 0; i < maxcnt; ++ i )
		tree2.Delete( r[ order[i] ] ); 
	finish = clock();
	cout << "回溯版本: " << (double)(finish-start)/CLOCKS_PER_SEC << "  " << "merge count: " << tree2.MergeCnt 
		<< " from key: " << tree2.FromCnt << " total cnt: " << tree2.MergeCnt+tree2.FromCnt << endl;
	
	return 0;
}


結果如下:

test insertion...
算法導論: 1.151  split count: 18922
回溯版本: 0.952  split count: 9857
test deletion...
算法導論: 0.552  merge count: 13615 from key: 227703 total cnt: 241318
回溯版本: 0.804  merge count: 5131 from key: 6516 total cnt: 11647

再次運行,結果如下:

test insertion...
算法導論: 1.286  split count: 18844
回溯版本: 0.919  split count: 9875
test deletion...
算法導論: 0.579  merge count: 13523 from key: 291994 total cnt: 305517
回溯版本: 0.809  merge count: 5166 from key: 6503 total cnt: 11669


  有點不明白的是,回溯版本明明比《算法導論》版本少了很多的節點合併和“借”關鍵字次數,可運行的時間反而比《算法導論》版本高,估計我代碼裏實現的不夠高效。


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