[英]C++ Object Creation Time
所以我正在构建一个 A* 搜索类型的东西,并在我的算法中需要时创建如下对象。 问题是,它们每一个都需要 1 秒的时间来创建。 我的搜索需要 40 秒,其中 39 秒是 object 创建的。
我真的一点头绪都没有。 很新。 任何帮助表示赞赏。
class Node{
private:
int numAncestors;
float gvalue;
float hvalue;
float fvalue;
int adj;
Node* parent;
public:
inline Node(int vertex, int goal, vector< vector<double> > xy){
adj = vertex - 1;
float x1 = (float)xy[vertex-1][0];
float y1 = (float)xy[vertex-1][1];
float x2 = (float)xy[goal-1][0];
float y2 = (float)xy[goal-1][1];
hvalue = sqrtf((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
//fvalue = hvalue + gvalue;
}
inline float getF(){
return hvalue + gvalue;
}
inline void setG(float newG){
gvalue = newG;
}
inline float getG(){
return gvalue;
}
inline int getAncestors(){
return numAncestors;
}
void setAncestors(int ancestors){
numAncestors = ancestors;
}
void setParent(Node* n, vector< vector<double> > xy){
parent = n;
float x1 = (float)xy[n->getAdj()][0];
float y1 = (float)xy[n->getAdj()][1];
float x2 = (float)xy[adj][0];
float y2 = (float)xy[adj][1];
float x = sqrtf((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
setG(n->getG() + x);
setAncestors(n->getAncestors()+1);
}
inline Node* getParent(){
return parent;
}
inline int getAdj(){
return adj;
}
};
这需要.1 秒:
clock_t nodetest = clock();
Node* s = new Node(g,e,xy);
printf("Time taken: %.2fs\n", (double)(clock() - nodetest)/CLOCKS_PER_SEC);
这需要 0.0 秒:
clock_t thisLoop = clock();
float x1 = (float)xy[x-1][0];
float y1 = (float)xy[x-1][1];
float x2 = (float)xy[current->getAdj()][0];
float y2 = (float)xy[current->getAdj()][1];
float x = sqrtf((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
printf("Time taken: %.2fs\n", (double)(clock() - thisLoop)/CLOCKS_PER_SEC);
我原以为这可能是 object 的目的或其他原因,但似乎所有花费的时间都只是在 object 的创建中。
当您调用Node
构造函数时,您通过 value传递xy
,这意味着由整个数组制作副本。 您应该通过const reference传递它:
Node(int vertex, int goal, const vector<vector<double>> &xy)
这也应该为setParent
完成。
其他注意事项:
Node
构造函数不会初始化它的所有成员。 特别是parent
里面会有一个垃圾值,这可能会导致以后出现奇怪的错误。
Node
构造函数和setParent
共享一堆可以工作的代码。 这应该放在可以调用以避免代码重复的(私有)成员 function 中。
各种get
函数可以是const
,例如float getF() const;
.
您不需要inline
关键字,因为在 class 定义中定义的任何 function 都是隐式内联的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.