C++对象创建时间

问题描述 投票:0回答:1

所以我正在建立一个A*搜索之类的东西,并在需要的时候在我的算法中创建下面的对象。问题是,它们每个被创建的时间是0.1秒。我的搜索需要40秒,其中39秒是创建对象。

我真的是毫无头绪。挺新的。任何帮助感激不尽。

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;
    }
};

这需要0.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);

我本以为可能是对象在做什么或其他什么,但从这一点来看,全部时间都花在了创建对象上。

c++ performance object a-star
1个回答
3
投票

当你调用 Node 构造函数,你传递的是 xy 按价值意思是对整个数组进行复制。 你应该通过 参考文献:

Node(int vertex, int goal, const vector<vector<double>> &xy)

也应该这样做。setParent.

其他说明。

该文件是由中国人民大学出版社出版的。Node 构造函数并没有初始化它的所有成员。 特别是: parent 中会有一个垃圾值,这可能会导致以后出现奇怪的错误。

Node 构造函数和 setParent 共享一堆代码,做一些工作。 这应该放在一个可以调用的(私有)成员函数中,以避免代码重复。

各种 get 职能可 const譬如说. float getF() const;.

你不需要 inline 关键字,因为在类定义中定义的任何函数都是隐式内联的。

© www.soinside.com 2019 - 2024. All rights reserved.