内置mod('%')与自定义mod功能:提高模数运算的性能 [英] Built-in mod ('%') vs custom mod function: improve the performance of modulus operation
本文介绍了内置mod('%')与自定义mod功能:提高模数运算的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近我知道mod('%')运算符非常慢.所以我做了一个可以像%b一样工作的函数.但是它比mod运算符更快吗?
Recently I came to know that the mod('%') operator is very slow. So I made a function which will work just like a%b. But is it faster than the mod operator?
这是我的职能
int mod(int a, int b)
{
int tmp = a/b;
return a - (b*tmp);
}
推荐答案
根据钱德勒·卡鲁斯(Chandler Carruth)在CppCon 2015上的基准测试,最快的模运算符(在x86上,用Clang编译时)是:
According to Chandler Carruth's benchmarks at CppCon 2015, the fastest modulo operator (on x86, when compiled with Clang) is:
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
}
我建议您观看整个谈话,他将详细介绍为什么此方法比无条件使用%
更快.
I suggest that you watch the whole talk, he goes into more details on why this method is faster than just using %
unconditionally.
这篇关于内置mod('%')与自定义mod功能:提高模数运算的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文