[英]Finding minimum and maximum efficiently
I have two integer parameters a
and b
. 我有两个整数参数a
和b
。 And two integer variables max
and min
. 还有两个整数变量max
和min
。 I want to assign to max
the maximum of a
and b
and to min
the minimum of the two. 我想分配给max
最大的a
和b
和min
最小的两个。 I need to do this operation millions of times and so I want to optimize it. 我需要执行此操作数百万次,因此我想对其进行优化。 I am currently doing the following: 我目前正在执行以下操作:
min = a < b ? a : b;
max = a > b ? a : b;
The problem with this is that it requires two if statements. 问题是它需要两个if语句。 I am wondering if there is a better way to do this. 我想知道是否有更好的方法可以做到这一点。
std::tie(min, max) = std::minmax(a, b);
if (a < b)
{
min = a; max = b;
}
else
{
min = b; max = a;
}
You're probably optimizing prematurely. 您可能过早地进行了优化。 See what the compiler makes of it. 看看编译器如何处理它。
For a version with just one conditional, this is straightforward:- 对于只有一个条件的版本,这很简单:
if (a < b)
{
min = a;
max = b;
}
else
{
min = b;
max = a;
}
Or you might want to use some maths: 或者您可能想使用一些数学方法:
int absdiff = abs (a-b);
int sum = a+b;
max = (sum+absdiff)/2;
min = (sum-absdiff)/2;
You can trust compilers to optimize all that depending on the base type, you get rid of the branch and get a constant execution time (does not rely on predictors). 您可以信任编译器根据基本类型对所有内容进行优化,从而摆脱分支并获得恒定的执行时间(不依赖于预测变量)。
Edit: 编辑:
sample abs integer function on Intel processors : 英特尔处理器上的示例Abs整数函数:
cdq
xor eax, edx
sub eax, edx
min=a;max=b;
if(a>b) {
max=a;
min=b;
} //Here you don't even need an else statement, i don't know how much time does else take but if it does then you have saved it.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.