比较运算符的复杂性
Complexity of comparison operators
当数组x的值总是高于y时(例如1<x<2
和0<y<1
),为什么y[i] < x[i]
函数需要两倍的时间。此外,当比较0.5<x<1.5
和0<y<1
时,执行时间大约是0<x<1
和0<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 ();
}
一种解释是,如果第一个条件适用,会减少跳跃
第二种解释是关于分支预测,基本上,它可以"猜测"<result并应用下一个代码,而不管结果如何,并将其拖入失败,因此当相同的情况相对频繁地发生时,编译器可以更频繁地正确猜测。您可以在此处阅读更多信息:http://en.wikipedia.org/wiki/Branch_predication
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 具有未知值时的时间复杂性
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- delete[]运算符的时间复杂性
- 比较运算符的复杂性