【问题标题】:Complexity of comparison operators [duplicate]比较运算符的复杂性
【发布时间】:2015-05-29 08:21:24
【问题描述】:

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

我添加代码让您尝试理解我的意思。您可以通过增加和减少变量“偏移量(尝试偏移量=1和偏移量=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 ();
}

【问题讨论】:

  • 请不要定义你自己的MAX使用std::max

标签: c++ time-complexity


【解决方案1】:

一种解释是,如果第一个条件适用,则跳转较少,

第二个解释是关于分支断言,基本上,它可以“猜测”'http://en.wikipedia.org/wiki/Branch_predication

【讨论】:

  • 断言,没有a
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多