【性能优化】取模运算:x%n,当n是偶数时,可以用x&(n-1)替代
2019-04-14 08:21发布
生成海报
#include
void modulo_operation_opt()
{
int m = 100000;
int n = 100000;
double a, b;
//assert( (i%2n) == (i&(2n - 1)))
for (int i = 10; i--;)
{
assert((i % 4) == (i&(4-1)));
printf("%d : %d, %d
", i, i%4, i&(4-1));
}
a = ncnn::get_current_time();
//i%2n
for(int i = m;i--;)
for (int j = n;j--;)
{
i % 4;
}
b = ncnn::get_current_time();
printf("i mo (2n) time: %.5lf
", (b - a));
//i&(2n - 1)
a = ncnn::get_current_time();
for (int i = m; i--;)
for (int j = n; j--;)
{
i & 3;
}
b = ncnn::get_current_time();
printf("i & (2n - 1) time: %.5lf
", (b - a));
return;
}
要根据实际测试情况来考虑是否替换。
(end)
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮