为什么DFS在一棵树中较慢而在另一棵树中较快?

时间:2016-09-12 13:10:14

标签: c++ algorithm performance caching tree

更新:原来在解析器中存在生成树的错误。更多在最终编辑中。

T成为二叉树,这样每个内部节点都只有两个子节点。对于此树,我们希望编写一个函数,该函数为v中的每个节点T找到由v定义的子树中的节点数。

示例

输入

enter image description here

期望的输出

enter image description here

用红色表示我们想要计算的数字。树的节点将存储在一个数组中,让我们按照预先排序布局调用它TreeArray

对于上面的示例,TreeArray将包含以下对象:

10, 11, 0, 12, 13, 2, 7, 3, 14, 1, 15, 16, 4, 8, 17, 18, 5, 9, 6

树的节点由以下结构描述:

struct tree_node{

    long long int id; //id of the node, randomly generated
    int numChildren; //number of children, it is 2 but for the leafs it's 0
    int size; //size of the subtree rooted at the current node,
    // what we want to compute

    int pos; //position in TreeArray where the node is stored
    int lpos; //position of the left child
    int rpos; //position of the right child

    tree_node(){
        id = -1;
        size = 1;
        pos = lpos = rpos = -1;
        numChildren = 0;
    }

};

计算所有size值的函数如下:

void testCache(int cur){

    if(treeArray[cur].numChildren == 0){
        treeArray[cur].size = 1;
        return;
    }

    testCache(treeArray[cur].lpos);
    testCache(treeArray[cur].rpos);

    treeArray[cur].size = treeArray[treeArray[cur].lpos].size + 
    treeArray[treeArray[cur].rpos].size + 1;

}

我想了解为什么当T看起来像这样的函数时,这个函数更快(几乎就像一个左转链):

enter image description here

并且当T看起来像这样时更慢(几乎就像一个正确的链):

enter image description here

以下实验在Intel(R)Core(TM)i5-3470 CPU @ 3.20GHz上运行,内存为8 GB,L1缓存为256 KB,L2缓存为1 MB,L3缓存为6 MB。

图中的每个点都是以下for循环的结果(参数由轴定义):

for (int i = 0; i < 100; i++) {
        testCache(0);
}

enter image description here

n对应于节点总数,时间以秒为单位。我们可以看到很明显,当n增长时,当树看起来像一条左向链时,功能会快得多,即使节点数在两种情况下完全相同。

现在让我们试着找出瓶颈所在。我使用PAPI library来计算有趣的硬件计数器。

第一个计数器是说明,我们实际花了多少指令?当树木看起来不同时会有区别吗?

enter image description here

差异不大。看起来对于大输入,左转链需要较少的指令,但差别很小,所以我认为可以安全地假设它们都需要相同数量的指令。

看到我们已经将树存储在treeArray内的一个漂亮的预订单布局中,看看缓存中发生了什么是有意义的。不幸的是,对于L1缓存,我的计算机不提供任何计数器,但我有L2和L3。

让我们看看对L2缓存的访问。当我们在L1缓存中丢失时,会发生对L2缓存的访问,因此这也是L1未命中的间接计数器。

enter image description here

正如我们所看到的,正确的树需要更少的L1未命中,因此它似乎有效地使用了缓存。

enter image description here

对于L2未命中,正确的树似乎更有效。仍然没有任何迹象表明为什么正确的树木如此慢。让我们来看看L3。

enter image description here

在L3中,正确的树木会爆炸。所以问题似乎是在L3缓存中。不幸的是我无法解释这种行为背后的原因。为什么事情会在L3缓存中搞砸到正确的树木?

以下是整个代码和实验:

#include <iostream>
#include <fstream>
#define BILLION  1000000000LL

using namespace std;


/*
 *
 * Timing functions
 *
 */

timespec startT, endT;

void startTimer(){
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &startT);
}

double endTimer(){
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &endT);
    return endT.tv_sec * BILLION + endT.tv_nsec - (startT.tv_sec * BILLION + startT.tv_nsec);
}

/*
 *
 * tree node
 *
 */

//this struct is used for creating the first tree after reading it from the external file, for this we need left and child pointers

struct tree_node_temp{

    long long int id; //id of the node, randomly generated
    int numChildren; //number of children, it is 2 but for the leafs it's 0
    int size; //size of the subtree rooted at the current node
    tree_node_temp *leftChild;
    tree_node_temp *rightChild;

    tree_node_temp(){
        id = -1;
        size = 1;
        leftChild = nullptr;
        rightChild = nullptr;
        numChildren = 0;
    }

};

struct tree_node{

    long long int id; //id of the node, randomly generated
    int numChildren; //number of children, it is 2 but for the leafs it's 0
    int size; //size of the subtree rooted at the current node

    int pos; //position in TreeArray where the node is stored
    int lpos; //position of the left child
    int rpos; //position of the right child

    tree_node(){
        id = -1;
        pos = lpos = rpos = -1;
        numChildren = 0;
    }

};

/*
 *
 * Tree parser. The input is a file containing the tree in the newick format.
 *
 */

string treeNewickStr; //string storing the newick format of a tree that we read from a file
int treeCurSTRindex; //index to the current position we are in while reading the newick string
int treeNumLeafs; //number of leafs in current tree
tree_node ** treeArrayReferences; //stack of references to free node objects
tree_node *treeArray; //array of node objects
int treeStackReferencesTop; //the top index to the references stack
int curpos; //used to find pos,lpos and rpos when creating the pre order layout tree


//helper function for readNewick
tree_node_temp* readNewickHelper() {

    int i;
    if(treeCurSTRindex == treeNewickStr.size())
        return nullptr;

    tree_node_temp * leftChild;
    tree_node_temp * rightChild;

    if(treeNewickStr[treeCurSTRindex] == '('){
        //create a left child
        treeCurSTRindex++;
        leftChild = readNewickHelper();
    }

    if(treeNewickStr[treeCurSTRindex] == ','){
        //create a right child
        treeCurSTRindex++;
        rightChild = readNewickHelper();
    }

    if(treeNewickStr[treeCurSTRindex] == ')' || treeNewickStr[treeCurSTRindex] == ';'){
        treeCurSTRindex++;
        tree_node_temp * cur = new tree_node_temp();
        cur->numChildren = 2;
        cur->leftChild = leftChild;
        cur->rightChild = rightChild;
        cur->size = 1 + leftChild->size + rightChild->size;
        return cur;
    }

    //we are about to read a label, keep reading until we read a "," ")" or "(" (we assume that the newick string has the right format)
    i = 0;
    char treeLabel[20]; //buffer used for the label
    while(treeNewickStr[treeCurSTRindex]!=',' && treeNewickStr[treeCurSTRindex]!='(' && treeNewickStr[treeCurSTRindex]!=')'){
        treeLabel[i] = treeNewickStr[treeCurSTRindex];
        treeCurSTRindex++;
        i++;
    }

    treeLabel[i] = '\0';
    tree_node_temp * cur = new tree_node_temp();
    cur->numChildren = 0;
    cur->id = atoi(treeLabel)-1;
    treeNumLeafs++;

    return cur;
}

//create the pre order tree, curRoot in the first call points to the root of the first tree that was given to us by the parser
void treeInit(tree_node_temp * curRoot){

    tree_node * curFinalRoot = treeArrayReferences[curpos];

    curFinalRoot->pos = curpos;

    if(curRoot->numChildren == 0) {
        curFinalRoot->id = curRoot->id;
        return;
    }

    //add left child
    tree_node * cnode = treeArrayReferences[treeStackReferencesTop];
    curFinalRoot->lpos = curpos + 1;
    curpos = curpos + 1;
    treeStackReferencesTop++;
    cnode->id = curRoot->leftChild->id;
    treeInit(curRoot->leftChild);

    //add right child
    curFinalRoot->rpos = curpos + 1;
    curpos = curpos + 1;
    cnode = treeArrayReferences[treeStackReferencesTop];
    treeStackReferencesTop++;
    cnode->id = curRoot->rightChild->id;
    treeInit(curRoot->rightChild);

    curFinalRoot->id = curRoot->id;
    curFinalRoot->numChildren = 2;
    curFinalRoot->size = curRoot->size;

}

//the ids of the leafs are deteremined by the newick file, for the internal nodes we just incrementally give the id determined by the dfs traversal
void updateInternalNodeIDs(int cur){

    tree_node* curNode = treeArrayReferences[cur];

    if(curNode->numChildren == 0){
        return;
    }
    curNode->id = treeNumLeafs++;
    updateInternalNodeIDs(curNode->lpos);
    updateInternalNodeIDs(curNode->rpos);

}

//frees the memory of the first tree generated by the parser
void treeFreeMemory(tree_node_temp* cur){

    if(cur->numChildren == 0){
        delete cur;
        return;
    }
    treeFreeMemory(cur->leftChild);
    treeFreeMemory(cur->rightChild);

    delete cur;

}

//reads the tree stored in "file" under the newick format and creates it in the main memory. The output (what the function returns) is a pointer to the root of the tree.
//this tree is scattered anywhere in the memory.

tree_node* readNewick(string& file){

    treeCurSTRindex = -1;
    treeNewickStr = "";
    treeNumLeafs = 0;

    ifstream treeFin;

    treeFin.open(file, ios_base::in);
    //read the newick format of the tree and store it in a string
    treeFin>>treeNewickStr;
    //initialize index for reading the string
    treeCurSTRindex = 0;
    //create the tree in main memory
    tree_node_temp* root = readNewickHelper();

    //store the tree in an array following the pre order layout
    treeArray = new tree_node[root->size];
    treeArrayReferences = new tree_node*[root->size];
    int i;
    for(i=0;i<root->size;i++)
        treeArrayReferences[i] = &treeArray[i];
    treeStackReferencesTop = 0;

    tree_node* finalRoot = treeArrayReferences[treeStackReferencesTop];
    curpos = treeStackReferencesTop;
    treeStackReferencesTop++;
    finalRoot->id = root->id;
    treeInit(root);

    //update the internal node ids (the leaf ids are defined by the ids stored in the newick string)
    updateInternalNodeIDs(0);
    //close the file
    treeFin.close();

    //free the memory of initial tree
    treeFreeMemory(root);
    //return the pre order tree
    return finalRoot;

}

/*
 *
 *
 * DOT FORMAT OUTPUT --- BEGIN
 *
 *
 */

void treeBstPrintDotAux(tree_node* node, ofstream& treeFout) {

    if(node->numChildren == 0) return;

    treeFout<<"    "<<node->id<<" -> "<<treeArrayReferences[node->lpos]->id<<";\n";
    treeBstPrintDotAux(treeArrayReferences[node->lpos], treeFout);

    treeFout<<"    "<<node->id<<" -> "<<treeArrayReferences[node->rpos]->id<<";\n";
    treeBstPrintDotAux(treeArrayReferences[node->rpos], treeFout);

}

void treePrintDotHelper(tree_node* cur, ofstream& treeFout){
    treeFout<<"digraph BST {\n";
    treeFout<<"    node [fontname=\"Arial\"];\n";

    if(cur == nullptr){
        treeFout<<"\n";
    }
    else if(cur->numChildren == 0){
        treeFout<<"    "<<cur->id<<";\n";
    }
    else{
        treeBstPrintDotAux(cur, treeFout);
    }

    treeFout<<"}\n";
}

void treePrintDot(string& file, tree_node* root){

    ofstream treeFout;
    treeFout.open(file, ios_base::out);
    treePrintDotHelper(root, treeFout);
    treeFout.close();

}

/*
 *
 *
 * DOT FORMAT OUTPUT --- END
 *
 *
 */

/*
 * experiments
 *
 */

tree_node* T;
int n;

void testCache(int cur){

    if(treeArray[cur].numChildren == 0){
        treeArray[cur].size = 1;
        return;
    }

    testCache(treeArray[cur].lpos);
    testCache(treeArray[cur].rpos);

    treeArray[cur].size = treeArray[treeArray[cur].lpos].size + treeArray[treeArray[cur].rpos].size + 1;

}


int main(int argc, char* argv[]){

    string Tnewick = argv[1];
    T = readNewick(Tnewick);

    n = T->size;
    double tt;

    startTimer();
    for (int i = 0; i < 100; i++) {
        testCache(0);
    }

    tt = endTimer();
    cout << tt / BILLION << '\t' << T->size;
    cout<<endl;

    return 0;
}

键入g++ -O3 -std=c++11 file.cpp进行编译 通过输入./executable tree.txt来运行。在tree.txt中,我们将树存储在newick format

Here是一个剩下的树,有10 ^ 5个叶子

Here是一棵正确的树,有10 ^ 5片叶子

我得到的运行时间: 左转树约0.07秒 正确的树木约0.12秒

我为长篇大论道歉,但鉴于问题似乎有多么狭窄,我无法找到更好的方式来描述它。

提前谢谢!

修改

在MrSmith42回答之后,这是一个跟进编辑。我知道地方扮演着非常重要的角色,但我不确定我是否明白这就是这种情况。

对于上面的两个示例树,让我们看看我们如何随着时间的推移访问内存。

对于左转树:

enter image description here

对于正确的树:

enter image description here

对我来说,似乎在这两种情况下我们都有本地访问模式。

修改

这是关于条件分支数量的图表:

enter image description here

这是关于分支错误预测数量的图表:

enter image description here

Here是一棵剩下的树,有10 ^ 6片叶子

Here是一棵正确的树,有10 ^ 6片叶子

最终编辑:

我想为浪费每个人的时间而道歉,我使用的解析器有一个参数,用于&#34;离开&#34;或&#34;对&#34;我想让我的树看起来像。这是一个浮点数,它必须接近0才能使它继续前进并接近1以使其正确运行。但是,要使其看起来像链条,它必须非常小,例如0.0000000010.999999999。对于小输入,即使像0.0001这样的值,树也看起来像一条链。我认为这个数字足够小,而且它也会为更大的树木提供链条,但是我将证明并非如此。如果使用0.000000001之类的数字,解析器会因浮点问题而停止工作。

vadikrobot的回答显示我们有地方问题。受他的实验启发,我决定概括上面的访问模式图,看看它不仅在示例树中,而且在任何树中都表现得如何。

我修改了vadikrobot的代码,如下所示:

void testCache(int cur, FILE *f) {

    if(treeArray[cur].numChildren == 0){
        fprintf(f, "%d\t", tim++);
        fprintf (f, "%d\n", cur);
        treeArray[cur].size = 1;
        return;
    }

    fprintf(f, "%d\t", tim++);
    fprintf (f, "%d\n", cur);
    testCache(treeArray[cur].lpos, f);
    fprintf(f, "%d\t", tim++);
    fprintf (f, "%d\n", cur);
    testCache(treeArray[cur].rpos, f);
    fprintf(f, "%d\t", tim++);
    fprintf (f, "%d\n", cur);
    fprintf(f, "%d\t", tim++);
    fprintf (f, "%d\n", treeArray[cur].lpos);
    fprintf(f, "%d\t", tim++);
    fprintf (f, "%d\n", treeArray[cur].rpos);
    treeArray[cur].size = treeArray[treeArray[cur].lpos].size + 
    treeArray[treeArray[cur].rpos].size + 1;
}

错误解析器生成的访问模式

让我们看一下有10片叶子的左树。

enter image description here

看起来非常好,正如上图所示(我在上面的图中只忘了这样一个事实:当我们找到一个节点的大小时,我们也访问该节点的大小参数,cur上面的源代码。)

让我们看一下有100片叶子的左树。

enter image description here

看起来像预期的那样。千片叶子怎么样?

enter image description here

这绝对不是预期的。右上角有一个小三角形。原因是因为树看起来不像是一个左转链,最后有一个小的子树悬挂在某个地方。当叶子为10 ^ 4时,问题变得更大。

enter image description here

让我们来看看右树的情况。当叶子是10:

enter image description here

看起来不错,100片叶子怎么样?

enter image description here

看起来也不错。这就是为什么我质疑右树的地方,对我来说,两者似乎至少是理论本地的。现在,如果你尝试增加尺寸,就会发生一些有趣的事情:

1000片叶子:

enter image description here

对于10 ^ 4片叶子,事情变得更加混乱:

enter image description here

正确解析器生成的访问模式

我没有使用那个通用解析器,而是为这个特定问题创建了一个:

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char* argv[]){

    if(argc!=4){
        cout<<"type ./executable n{number of leafs} type{l:left going, r:right going} outputFile"<<endl;
        return 0;
    }

    int i;

    int n = atoi(argv[1]);

    if(n <= 2){cout<<"leafs must be at least 3"<<endl; return 0;}

    char c = argv[2][0];

    ofstream fout;
    fout.open(argv[3], ios_base::out);

    if(c == 'r'){

        for(i=0;i<n-1;i++){

            fout<<"("<<i<<",";

        }
        fout<<i;
        for(i=0;i<n;i++){
            fout<<")";
        }
        fout<<";"<<endl;

    }
    else{

        for(i=0;i<n-1;i++){
            fout<<"(";
        }

        fout<<1<<","<<n<<")";

        for(i=n-1;i>1;i--){
            fout<<","<<i<<")";
        }
        fout<<";"<<endl;

    }

    fout.close();


return 0;
}

现在访问模式看起来像预期的那样。

对于10 ^ 4叶子的左树:

enter image description here

在黑色部分,我们从低处到高处,但前一个低点和当前低点之间的距离很小,前一个高点和当前高点相同。因此,缓存必须足够智能以容纳两个块,一个用于低位,一个用于高位,从而产生少量缓存未命中。

对于10 ^ 4叶子的右树:

enter image description here

The original experiments again。这次我只能尝试10 ^ 5片叶子,因为正如Mysticial注意到的那样,由于树木的高度我们会得到堆栈溢出,这在以前的实验中并非如此,因为高度小于预期的那个。

时间方面他们似乎表现相同,但缓存和分支不是。正确的树木在分支预测中击败了左边的树木,左边的树木在缓存中击败了正确的树木。

也许我的PAPI使用错误,从perf输出

左树:

enter image description here

正确的树木:

enter image description here

我可能再次搞砸了一些事情,我为此道歉。我把我的尝试包括在内,以防万一有人想继续调查。

2 个答案:

答案 0 :(得分:2)

由于节点在我们的内存中的位置,缓存未命中是不同的。如果您按照它们在memmory中的顺序访问节点,则缓存可能已经从缓存中的ram加载它们(因为加载缓存页面(很可能大于您的一个节点))。

如果以随机顺序(透视到RAM中的位置)或以相反的顺序访问节点,则更有可能缓存尚未从RAM加载它们。

因此,差异不是因为树的结构,而是因为RAM中树节点的位置与您要访问它们的顺序相比。

编辑:(在访问模式添加到问题后):

正如您在访问模式图表中看到的那样:
&#34;左转树&#34; 上,访问在大约一半的访问后从低到高的索引跳转。因此随着距离的增长和增长,下半年可能总会导致缓存未命中 在&#34;正在进行的树&#34; 上,后半部分至少有2个节点彼此靠近(按访问顺序),接下来的两个节点有时会有点运气相同的缓存页面。

答案 1 :(得分:2)

更新:

我在时间上绘制了数组中被访问元素的数量

void testCache(int cur, FILE *f) {
   if(treeArray[cur].numChildren == 0){
       fprintf (f, "%d\n", cur);
       treeArray[cur].size = 1;
       return;
   }

   fprintf (f, "%d\n", cur);
   testCache(treeArray[cur].lpos, f);
   fprintf (f, "%d\n", cur);
   testCache(treeArray[cur].rpos, f);

   fprintf (f, "%d\n", treeArray[cur].lpos);
   fprintf (f, "%d\n", treeArray[cur].rpos);
   treeArray[cur].size = treeArray[treeArray[cur].lpos].size + treeArray[treeArray[cur].rpos].size + 1;
}

结果我绘制了结果文本文件的999990元素: enter image description here

你可以看到,对于左侧树,所有元素都是本地访问的,但对于正确的元素,访问时存在不均匀性。

OLD:

我尝试使用valgrind计算内存读取次数。 对于正确的

valgrind --tool=callgrind --cache-sim ./a.out right
==11493== I   refs:      427,444,674
==11493== I1  misses:          2,288
==11493== LLi misses:          2,068
==11493== I1  miss rate:        0.00%
==11493== LLi miss rate:        0.00%
==11493== 
==11493== D   refs:      213,159,341  (144,095,416 rd + 69,063,925 wr)
==11493== D1  misses:     15,401,346  ( 12,737,497 rd +  2,663,849 wr)
==11493== LLd misses:        329,337  (      7,935 rd +    321,402 wr)
==11493== D1  miss rate:         7.2% (        8.8%   +        3.9%  )
==11493== LLd miss rate:         0.2% (        0.0%   +        0.5%  )
==11493== 
==11493== LL refs:        15,403,634  ( 12,739,785 rd +  2,663,849 wr)
==11493== LL misses:         331,405  (     10,003 rd +    321,402 wr)
==11493== LL miss rate:          0.1% (        0.0%   +        0.5%  )

和左一个

valgrind --tool=callgrind --cache-sim=yes ./a.out left

==11496== I   refs:      418,204,722
==11496== I1  misses:          2,327
==11496== LLi misses:          2,099
==11496== I1  miss rate:        0.00%
==11496== LLi miss rate:        0.00%
==11496== 
==11496== D   refs:      204,114,971  (135,076,947 rd + 69,038,024 wr)
==11496== D1  misses:     19,470,268  ( 12,661,123 rd +  6,809,145 wr)
==11496== LLd misses:        306,948  (      7,935 rd +    299,013 wr)
==11496== D1  miss rate:         9.5% (        9.4%   +        9.9%  )
==11496== LLd miss rate:         0.2% (        0.0%   +        0.4%  )
==11496== 
==11496== LL refs:        19,472,595  ( 12,663,450 rd +  6,809,145 wr)
==11496== LL misses:         309,047  (     10,034 rd +    299,013 wr)
==11496== LL miss rate:          0.0% (        0.0%   +        0.4%  )

正如你所看到的那样,在'右'的情况下读'rd'的内存数量大于左边