有没有理由使用Math.floor(x)而不是(int)x来表示正数?

时间:2015-09-05 20:37:50

标签: java

似乎Math.floor(x)的速度低于此测试中建议的(int) x

public final class FloorRunningTime {
    public static void main(final String[] args) {
        final double number = 4999.7;

        floorMethod(number);
        downcastMethod(number);

    }

    private static void floorMethod(final double number) {
        long start = System.nanoTime();
        final int floorValue = (int) Math.floor(number);
        long duration = System.nanoTime() - start;
        System.out.printf("Floor value is: %d. Running time (nanoseconds): %d.%n", floorValue,
            duration);
    }

    private static void downcastMethod(final double number) {
        long start = System.nanoTime();
        final int floorValue = (int) number;
        long duration = System.nanoTime() - start;
        System.out.printf("Floor value is: %d. Running time (nanoseconds): %d.%n", floorValue,
            duration);
    }
}

此次运行的输出为:

Floor value is: 4999. Running time (nanoseconds): 807820.
Floor value is: 4999. Running time (nanoseconds): 236.

这可能会对运行重复性呼叫产生影响,以便为不同的号码设置不同。

在对正数进行操作时,是否应该使用Math.floor(x)代替(int) x

0 个答案:

没有答案