0

我正在尝试设计一个和弦系统..

问题是我的系统工作正常,如果大小像 10-20 行 addPeer、removePeer 等。

但是当我用 5000 行命令文件测试它时。

前几百个相当快,但随着程序加载越来越多的行,它开始变慢..

由于程序的要求是测试我的程序设计,我不能使用线程。

我听说指针是让事情更快完成的好方法,但是我如何在我的情况下使用指针。

这是我的班级标题..

class chord 
{
public:
chord();
~chord();

struct fingerTable {
int index;
int key;
};

struct node {
int nodeid;
vector<fingerTable> fTable;
vector<string> data;
};

void addPeer(int);

vector<node> cNode;
vector<fingerTable> fTable;

/* SOME more functions ..*/
};

这是我的 addPeer 函数

void chord::addPeer(int id)
{
//id = node ID
int fIndex,nextNode;
node newNode;
vector<fingerTable> ft1;
vector<string> data1;
//increment indexCounter
//indexCounter++;

newNode.nodeid = id;
//insert a blank fingerTable first.
newNode.fTable = ft1;
//insert a blank data first.
newNode.data = data1;

//push back node to vector chord Index Node
cNode.push_back(newNode);
//indexCounter++;
//perform finger table computation

//sort it base on its NodeID
sort(cNode.begin(),cNode.end(),sortByNodeID);

for(int i=0;i<cNode.size();i++)
{
if(cNode[i].nodeid==id)
{
fIndex=i;
}
}//end for loop to loop finding index of node

if(fIndex!=cNode.size()-1)
{
//if not last element
nextNode=fIndex+1;
}
else
{
nextNode=0;
}

//now we get the message vector of the next node and do a datashift on it.
data1 = cNode[nextNode].data;
//clear its data away so we can empty it and re-arrange it.
cNode[nextNode].data.clear();
//performing data shift function
dataShift(data1,fIndex-1);

if(id!=0)
{
cout << "PEER " << id << " inserted."<< endl;
}

}//end addPeer

我的问题是,我可以为这个函数 addPeer 即兴创作哪一部分来使整个程序更快地执行这些行。因为执行几百行时它变得非常慢。

4

2 回答 2

1

这正在减慢速度,因为您不断地进行分类。你应该试探。使用排序结构,如std::map<int,node>.

于 2013-02-16T18:24:57.343 回答
0

改变你的容器。

通过使用std::vector,您的算法大部分时间都在将和弦复制到错误的位置。

如果您希望对和弦进行排序,请考虑使用std::set而不是std::vector.

于 2013-02-16T17:54:08.000 回答