为什么G ++编译器不能以同样的方式处理这两个函数?

jsg*_*guy 28 c++ performance

我有一个A零和一个数组.我想找到所有数字的总和A.我想测试两个函数:

第一个功能

void test1(int curIndex){
    if(curIndex == size) return;
    test1(curIndex+1);
    s+=A[curIndex];
}
Run Code Online (Sandbox Code Playgroud)

第二功能

void test2(int curIndex){
    if(curIndex == size) return;
    s+=A[curIndex];
    test2(curIndex+1);
}
Run Code Online (Sandbox Code Playgroud)

我使用PAPI库来计算指令数量,这是整个实验:

#include <iostream>
#include <fstream>
#include "Statistics.h"

using namespace std;


int size;
int *A;
int s;

void test3(int curIndex){
    if(curIndex == size) return;
    test3(curIndex+1);
    s+=A[curIndex];
}

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

    size = atoi(argv[1]);
    if(argc!=2){
        cout<<"type ./executable size{odd integer}"<<endl;
        return 1;
    }
    if(size%2!=1){
        cout<<"size must be an odd number"<<endl;
        return 1;
    }
    A = new int[size];
    int i;
    for(i=0;i<size;i++){
        if(i%2==0){
            A[i] = false;
        }
        else{
            A[i] = true;
        }
    }

    Statistics stat(1);
    stat.start();
    test3(0);
    stat.stop();
    stat.printWithHelp();
    cout<<s<<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是Statistics.h文件:

#ifndef TRIPLETPARSER_STATISTICS_H
#define TRIPLETPARSER_STATISTICS_H

#include <time.h>
#include <unistd.h>
#include <fstream>
#include <papi.h>
#include <iostream>
#include <iostream>

#define BILLION  1000000000LL

using namespace std;

class Statistics {

private:
    timespec s, e;
    /*
    PAPI_BR_CN  Conditional branch instructions
    PAPI_BR_INS     Branch instructions
    PAPI_BR_MSP     Conditional branch instructions mispredicted
    PAPI_BR_NTK     Conditional branch instructions not taken
    PAPI_BR_PRC     Conditional branch instructions correctly predicted
    PAPI_BR_TKN     Conditional branch instructions taken
    PAPI_BR_UCN     Unconditional branch instructions
    PAPI_BRU_IDL    Cycles branch units are idle
    PAPI_BTAC_M     Branch target address cache misses

    PAPI_TLB_DM     Data translation lookaside buffer misses
    */
    int events[10];  // , PAPI_L2_TCA,PAPI_L3_TCM,PAPI_L3_TCA PAPI_BR_CN, PAPI_BR_PRC}; //type of events we are interested in
    int num_hwcntrs;  //total amount of events stored in 'events' array
    long long values[10];
    long long counters[10];

    void handle_error(int err){
        std::cerr << "PAPI error: " << err << std::endl;
    }

public:
    Statistics(int papi){
        for(size_t i = 0; i< 10; i++)
            counters[i]=0.0;

        switch(papi){
            case 0:
                num_hwcntrs = 0;
                break;
            case 1:
                num_hwcntrs = 6;
                events[0] = PAPI_L2_TCA;
                events[1] = PAPI_L3_TCA;
                events[2] = PAPI_L3_TCM;
                events[3] = PAPI_TOT_INS;
                events[4] = PAPI_BR_INS;
                events[5] = PAPI_BR_MSP;
                break;
        }

    }

    void start(){

        for(size_t i = 0; i< 10; i++)
            counters[i]=0.0;

        if (num_hwcntrs != 0 && PAPI_start_counters(events, num_hwcntrs) != PAPI_OK)
            handle_error(1);
    }


    void start(float ratio){

        if (num_hwcntrs != 0 && PAPI_start_counters(events, num_hwcntrs) != PAPI_OK)
            handle_error(1);
    }


    void stop(){
        if (num_hwcntrs != 0 && PAPI_stop_counters(values, num_hwcntrs) != PAPI_OK)
            handle_error(1);
        update();
    }

    void stop(float ratio){
        if (num_hwcntrs != 0 && PAPI_stop_counters(values, num_hwcntrs) != PAPI_OK)
            handle_error(1);
        update();
    }


    void update(){
        for(size_t i = 0; i < num_hwcntrs; i++)
            counters[i] += values[i];
    }

    void print(){
        for(int i=0;i<num_hwcntrs;i++)
            std::cout << counters[i] << "\t";
        //cout<<"L2 cache miss ratio: "<<counters[1]/(double)counters[0]<<endl;
        //cout<<"L3 cache miss ratio: "<<counters[3]/(double)counters[2]<<endl;
    }

    void printWithHelp(){
        cout<<"L2 accesses: "<<counters[0]<<endl;
        cout<<"L2 miss/access ratio: "<<(double)counters[1]/counters[0]<<endl;
        cout<<"L3 accesses: "<<counters[1]<<endl;
        cout<<"L3 misses: "<<counters[2]<<endl;
        cout<<"L3 miss/access ratio: "<<(double)counters[2]/counters[1]<<endl;
        cout<<"Instructions: "<<counters[3]<<endl;
        cout<<"Branches: "<<counters[4]<<endl;
        cout<<"Branch mispredictions: "<<counters[5]<<endl;
        cout<<"Branch miss/predict ratio: "<<(double)counters[5]/counters[4]<<endl;
    }

    void print(float avg_ratio){
        for (int i = 0; i<num_hwcntrs; i++)
            std::cout << (double)(avg_ratio*counters[i]) << "\t";
    }

};

#endif //TRIPLETPARSER_STATISTICS_H
Run Code Online (Sandbox Code Playgroud)

这是我从第一个函数获得的输出,当大小A111,111

L2 accesses: 24126
L2 miss/access ratio: 0.131559
L3 accesses: 3174
L3 misses: 587
L3 miss/access ratio: 0.18494
Instructions: 1022776
Branches: 178113
Branch mispredictions: 6976
Branch miss/predict ratio: 0.0391661
Run Code Online (Sandbox Code Playgroud)

这是我从第二个函数获得的输出,当大小A111,111

L2 accesses: 7090
L2 miss/access ratio: 0.163752
L3 accesses: 1161
L3 misses: 507
L3 miss/access ratio: 0.436693
Instructions: 555860
Branches: 111189
Branch mispredictions: 25
Branch miss/predict ratio: 0.000224842
Run Code Online (Sandbox Code Playgroud)

为什么结果有差异?指令减少一半,分支错误预测几乎消除.这里发生了什么?

Kri*_*ten 55

你的第二个函数是尾递归.这意味着编译器可以将其优化为:

void test2(int curIndex){
  while(true)
  {
    if(curIndex == size) return;
    s+=A[curIndex];
    curIndex = curIndex + 1;
  }
}
Run Code Online (Sandbox Code Playgroud)

这显着减少了指令的数量.它还减少了(最多)一个所需的堆栈帧数.因此,它使用了更少的内存,从而减少了缓存未命中数.

编译器无法对第一个函数进行此优化.

更新:有些人问为什么编译器无法在第一个函数上进行优化.

让我们从观察函数开始不是尾递归的.如果最后发生的事情是对同一函数的递归调用,然后返回该递归调用的结果(如果有的话),则函数是尾递归的.

显然,第一个函数不是这种情况,s+=A[curIndex];在递归调用之后执行.

那么人们就会问为什么编译器无法将第一个函数转换为第二个函数.

问题是"为什么G ++没有这个功能?" 这个问题的答案总是一样的.默认情况下,功能未实现; G ++没有该功能,因为没有人为客户设计,实现和交付该功能.

这应该是它的结束,但当然人们会想知道为什么没有人设计,实现和测试这个功能.好吧,也许没有人想过这样做.但更重要的是,这个功能远非微不足道.

首先,编译器必须理解这一点

test1(curIndex+1);
s+=A[curIndex];
Run Code Online (Sandbox Code Playgroud)

s+=A[curIndex];
test1(curIndex+1);
Run Code Online (Sandbox Code Playgroud)

是等价的.这是一个非常重要的观察,因为从机械的角度来看,它们并不相同!实际上,第一个有效地从数组的末尾循环到开始,而第二个从开始到结束循环.那是一样的吗?当A是int*(和int中的s)时,它会产生相同的结果,但在其他情况下则不会(例如,当A是double*且s是double时).我们希望编译器能够那么聪明吗?

所以这里我们有一个潜在的功能,实施成本很高.但如果收益很高,那么成本可能是值得的.好处高吗?我猜这在实际代码中发生的很少,即开发人员可能会编写第二个表单.所以你有它:一个昂贵的功能,几乎没有任何好处.恕我直言,编译器开发人员明智地将宝贵的时间花在更有用的功能上.

  • @zwol完全正确!这个问题不是一个关于gcc在代码推理上有多糟糕的例子,而是一个关于问题多么简单的例子,并且看起来非常像编译器的暂停问题 (16认同)
  • @Yakk在像C++这样的语言中,证明你可以将_any_操作与非inlinable函数调用交换非常困难,以至于许多编译器甚至都不打扰.我知道GCC _can_至少在某些情况下可以做到这一点,因为它已经被明确通知的函数(带有`__attribute__`)没有副作用,但这不是一个函数. (12认同)
  • 但最大的问题是:为什么编译器无法优化第一个函数?或者:是否有编译器进行此优化?优化是否与C++标准一致? (2认同)
  • @knivil - 优化的问题始终是"一致的程序可以说出差异吗?" 在符合的程序中无法检测到缓存命中或未命中. (2认同)
  • @knivil请注意,我只讨论尾部*递归*函数的优化,这是尾部调用优化的一个特例.在递归的情况下,只涉及一个函数,并且很容易在源代码中演示优化.一般TCO用跳转替换一个调用,可能进入另一个函数的主体,并且不能总是在源代码中演示.根据调用约定,虽然在汇编级别仍然相对容易. (2认同)