package com.heu.wsq.basic;
/**
* 测试取模与取余的时间消耗
* 1.对正数取模和取余是一样的
* 2.当取模的长度为2的n次方时,取余操作和len-1进行"余"运算是一样的
* @author wsq
* @date 2021/4/6
*/
public class MoldTest {
public static void main(String[] args) {
long preTime = System.currentTimeMillis();
long times = 100000000L;
long mod1 = 0L;
int n = 1888888888;
// 长度为2的10次方
int len = 1024;
for(int i = 0; i < times; i++){
mod1 = n % len;
}
long currTime1 = System.currentTimeMillis();
long mod2 = 0L;
for(int i = 0; i < times; i++){
mod2 = n & (len - 1);
}
long currTime2 = System.currentTimeMillis();
System.out.println("mod1:" + mod1 + ", cost : " + (currTime1 - preTime));
System.out.println("mod2:" + mod2 + ", cost : " + (currTime2 - currTime1));
}
}
output:
mod1:56, cost : 58
mod2:56, cost : 49
测试取模与取余的时间消耗
最新推荐文章于 2023-07-20 11:07:29 发布
该博客通过代码测试了在Java中使用取模运算 `%` 和位运算 `&` 进行求余操作的时间消耗。实验表明,当取模的数值为2的n次方时,位运算与取模运算在性能上有明显差异,位运算(`n&(len-1)`)通常更快。这对于需要高效计算的场景,尤其是大数据处理和算法优化,具有一定的指导意义。
447

被折叠的 条评论
为什么被折叠?



