22

Why does the y[i] < x[i] function take twice the time when array x is always higher in value than y (for ex 1<x<2, and 0<y<1). In addition, when comparing 0.5<x<1.5, and 0<y<1, the execution time is about 1.5x the case where 0<x<1, and 0<y<1. This is assuming that both x and y are long arrays.

I add the code for you to try and get what I mean. you can offset the array x by increasing and decreasing the variable "offset (try offset =1 and offset =0); The code will store the execution time for the loops in the file Beta.

code is :

#include <iostream>
#include <array>
#include <time.h>
#include <math.h>
using namespace std;
#define MAX(x,y) ((x) > (y) ? (x) : (y))

int main()
{
ofstream myfile_Beta;
myfile_Beta.open ("Beta.txt");
clock_t begin_time = clock();
clock_t total_time;
srand (time(NULL));

double offset =0.0;

int m=0;
for(int k=0;k<10000;k++)
    {
    m=1;
    double M[75720],x[75720],y[75720];

    for (int i=0;i<75720;i++)
    {

        x[i]=+(rand()%1024)/1024.0* 1.0 + offset ;
        y[i]=+(rand()%1024)/1024.0* 1.0 + 0.00; 
    }
    begin_time = clock();
    for (int j=0;j<75720;j++)
    {
        M[j]=MAX(x[j],y[j]);
    }   
    total_time =clock () - begin_time;
    myfile_Beta <<float( total_time  )<<" "<<endl;
}
myfile_Beta.close ();
}
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
user304584
  • 487
  • 1
  • 3
  • 14
  • 4
    please don't define your own `MAX` use [`std::max`](http://en.cppreference.com/w/cpp/algorithm/max) – Mgetz Mar 25 '15 at 15:14

1 Answers1

1

One explanation is that there are less jumps if the first condition applies,

The second explanation regards branch predication, basically, where it could 'guess' the '<' result and apply the next code regardless of the result, and muck it on failure, so when you have the same condition happening relatively a lot, the compiler can guess it correctly more often. You can read more about it here: http://en.wikipedia.org/wiki/Branch_predication

Alon
  • 1,776
  • 13
  • 31