【java/math】位运算判断奇数和取余运算判断奇数的差别

【结论】

位运算稍快一点点。

【代码】

复制代码
package com.hy.lab.bitcalc;

public class Test {
    public static void main(String[] args){
        final int max=1000000000;
        int oddCnt=0;

        long startMs=System.currentTimeMillis();
        for(int i=0;i<max;i++) {
            if(isOddByBit(i)){
                oddCnt++;
            }
        }
        System.out.println("oddCnt="+oddCnt);
        long endMs=System.currentTimeMillis();
        System.out.println("isOddByBit耗时:"+ms2DHMS(startMs,endMs));

        oddCnt=0;

        startMs=System.currentTimeMillis();
        for(int i=0;i<max;i++) {
            if(isOddByMod(i)){
                oddCnt++;
            }
        }
        System.out.println("oddCnt="+oddCnt);
        endMs=System.currentTimeMillis();
        System.out.println("isOddByMod耗时:"+ms2DHMS(startMs,endMs));
    }

    // 位运算判断奇数
    private static boolean isOddByBit(int num){
        return (num & 1)==1;
    }

    // 取余运算判断奇数
    private static boolean isOddByMod(int num){
        return (num % 2)==1;
    }

    private static String ms2DHMS(long startMs, long endMs) {
        String retval = null;
        long secondCount = (endMs - startMs) / 1000;
        String ms = (endMs - startMs) % 1000 + "ms";

        long days = secondCount / (60 * 60 * 24);
        long hours = (secondCount % (60 * 60 * 24)) / (60 * 60);
        long minutes = (secondCount % (60 * 60)) / 60;
        long seconds = secondCount % 60;

        if (days > 0) {
            retval = days + "d" + hours + "h" + minutes + "m" + seconds + "s";
        } else if (hours > 0) {
            retval = hours + "h" + minutes + "m" + seconds + "s";
        } else if (minutes > 0) {
            retval = minutes + "m" + seconds + "s";
        } else if(seconds > 0) {
            retval = seconds + "s";
        }else {
            return ms;
        }

        return retval + ms;
    }
}
复制代码

输出:

第一次

oddCnt=500000000
isOddByBit耗时:1s359ms
oddCnt=500000000
isOddByMod耗时:1s860ms

第二次

oddCnt=500000000
isOddByBit耗时:1s406ms
oddCnt=500000000
isOddByMod耗时:1s516ms

第三次

oddCnt=500000000
isOddByBit耗时:1s297ms
oddCnt=500000000
isOddByMod耗时:1s547ms

END

posted @   逆火狂飙  阅读(91)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2017-06-30 【Canvas与艺术】绘制绿圈三红五星Premium Quality标志
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东
点击右上角即可分享
微信分享提示