【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 @ 2022-06-30 19:01  逆火狂飙  阅读(89)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东