通过加法或减法比较大数字与小数字的速度

时间:2013-11-13 00:30:29

标签: java performance time-complexity

以下哪项操作更快? (我正在寻找计算机科学/理论解释)

boolean value = System.currentTimeMillis() - myTime > TEN_HOURS;

boolean value = System.currentTimeMillis()  >  myTime + TEN_HOURS;

1 个答案:

答案 0 :(得分:0)

只是为了好玩,这是一个你可以自己运行的快速测试:

public class StrangeComparison {

    private static final long TEN_HOURS = 1000 * 60 * 60 * 10; // milliseconds -> seconds -> minutes -> hours -> ten

    private static final int NUM_COMPARISONS = 10000000;

    public static void main(String[] args) {

        long myTime = System.currentTimeMillis() - (TEN_HOURS / 2);

        long startTime = System.currentTimeMillis(); 
        for (int i = 0; i < NUM_COMPARISONS; i++) {
            boolean theValue = System.currentTimeMillis() - myTime > TEN_HOURS;
        }
        System.out.println("Took " + (System.currentTimeMillis() - startTime) + "ms for Comparison #1");

        startTime = System.currentTimeMillis(); 
        for (int i = 0; i < NUM_COMPARISONS; i++) {
            boolean theValue = System.currentTimeMillis() > TEN_HOURS + myTime;
        }
        System.out.println("Took " + (System.currentTimeMillis() - startTime) + "ms for Comparison #2");

    }
}

结果输出:

Took 401ms for Comparison #1
Took 400ms for Comparison #2