【发布时间】:2015-05-29 08:21:24
【问题描述】:
为什么当数组 x 的值总是高于 y 时,y[i] < x[i] 函数需要两倍的时间(例如 1<x<2 和 0<y<1)。另外,比较0.5<x<1.5和0<y<1时,执行时间大约是0<x<1和0<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