比较运算符的复杂性

use*_*584 15 c++ time-complexity

为什么y[i] < x[i]当数组x的值总是高于y(对于ex 1<x<2,和0<y<1)时,函数需要两倍的时间.另外,比较时0.5<x<1.5,0<y<1执行时间约为1.5倍的情况0<x<1,和0<y<1.这假设x和y都是长数组.

我为你添加了代码,试着去理解我的意思.您可以通过增加和减少变量"offset(try offset = 1和offset = 0)来偏移数组x;代码将在文件Beta中存储循环的执行时间.

代码是:

#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 ();
}
Run Code Online (Sandbox Code Playgroud)

Alo*_*lon 1

一种解释是,如果第一个条件适用,则跳转次数会减少,

第二种解释基本上是关于分支预测,它可以“猜测”“<”结果并应用下一个代码,而不管结果如何,并在失败时将其丢弃,因此当相同的情况发生相对较多时,编译器可以更频繁地猜对。您可以在这里阅读更多相关信息: http://en.wikipedia.org/wiki/Branch_predicate