c++ - 内置模组 ('%' ) 与自定义模组函数 : improve the performance of modulus operation

标签 c++ modular-arithmetic

最近我了解到 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/

相关文章:

c++ - 具有大整数的 mod % 运算符的局限性

c++ - DirectX 11 文件无法打开源文件

赋值运算符中的 C++ 函数求值顺序

python - Python 中的模块化算法

algorithm - 模算术 (a*b/e)%m?

math - 模倒数和无符号整数

c++ - block 操作的特征矩阵库补码

C++ 为什么受约束的算法(例如 std::ranges::merge)也返回输入范围的结尾?

c++ - OpenCV VideoCapture 无法在 OSX 上打开相机

c++ - 求大 n 和 k 模 m 的二项式系数