最近我了解到 mod('%') 运算符非常慢。所以我做了一个函数,它会像 a%b 一样工作。但它比 mod 运算符快吗?
这是我的功能
int mod(int a, int b)
{
int tmp = a/b;
return a - (b*tmp);
}
最佳答案
根据 Chandler Carruth's benchmarks at CppCon 2015 ,最快的模运算符 (在 x86 上,使用 Clang 编译时) 是:
int fast_mod(const int input, const int ceil) {
// apply the modulo operator only when needed
// (i.e. when the input is greater than the ceiling)
return input >= ceil ? input % ceil : input;
// NB: the assumption here is that the numbers are positive
}
我建议你观看整个演讲,他详细介绍了为什么这种方法比无条件地使用 %
更快。
关于c++ - 内置模组 ('%' ) 与自定义模组函数 : improve the performance of modulus operation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33333363/