比较运算符的复杂性

Complexity of comparison operators

本文关键字:复杂性 运算符 比较      更新时间:2023-10-16

当数组x的值总是高于y时(例如1<x<20<y<1),为什么y[i] < x[i]函数需要两倍的时间。此外,当比较0.5<x<1.50<y<1时,执行时间大约是0<x<10<y<1的情况的1.5倍。这是假设x和y都是长数组。

我添加代码是为了让你明白我的意思。您可以通过增加和减少变量"offset"来偏移数组x(尝试offset=1和offset=0);代码将把循环的执行时间存储在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 ();
}

一种解释是,如果第一个条件适用,会减少跳跃

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