0

I'm trying to find the length of the history pattern in the branch predictor of my computer's processor. I generated variable length array of bits and have if conditions based on the value of the bit. I will then plot the run time of different execution of the function and search for the knee in the graph. but I don't see any such point in the graph. What am I doing wrong? Any idea?

Here is my code:

vector<int> randomArr(int n)
{
    vector<int> arr (n);

  for ( int i=0; i <n; i++){
      arr[i] = rand() % 2;
  }

 return arr;
}

int branchy(vector<int> & arr){

      int a = 0 ;
      int b = 0 ;

      for ( int i = 0 ; i < arr.size() ; i++ ) {

          if ( arr[i] == 0)
              a++;
          else
              b++;
      }

    return a^b;
}


int main() {

    long int iterations = 100000; 
    int start_s;
    int stop_s;


    ofstream runtimesFile;
    runtimesFile.open("runtimesFile.txt");

    for (int j=0; j <iterations ; j++){
        vector<int> arr = randomArr(j);
        start_s=clock();
        branchy(arr);
        stop_s=clock();
        runtimesFile<< to_string(stop_s-start_s)<<"\n";


    }
    runtimesFile.close();
    return 0;
}

enter image description here

samira
  • 399
  • 1
  • 3
  • 12
  • 1
    Few things. You need to generate the random arr once *then* time a bunch of iters over it. Otherwise 1) you're measuring how long `rand()` takes, which is probably much longer than a branch and 2) the branch predictor can't learn the pattern of branches from history because it's different every time. Also, you need to make sure the compiler can't optimize away the branch by making sure it affects results -- you could do something like `if (bit) a++; else b++;` and return `a^b` or something. Finally, you should look at the extreme lower left of your graph, since the buffer's likely small. – twotwotwo Aug 09 '16 at 01:33
  • Thanks, I updated my post – samira Aug 10 '16 at 23:57

0 Answers0