javaeye上看到wenshao说System.nanoTime()很慢,比new Object()和System.currentTimeMillis()都慢很多。

我也测试了一把,测试环境:
OS
fedora 14 64位
CPU
I3 530
JAVA 版本
java version “1.6.0_22″ Java(TM) SE Runtime Environment (build 1.6.0_22-b04) Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03, mixed mode)

代码:

public class TimeTest {
    public static void main(String [] args) {
        test0();
        test1();
        test2();
    }
    static void test0() {
        long time = System.currentTimeMillis();
        for(int i=0; i < 10000 * 10000; ++i) {
            Object v = new Object();
        }
        System.out.println("test new Object(): " + (System.currentTimeMillis() – time));
    }
    static void test1() {
        long time = System.currentTimeMillis();
        for(int i=0; i < 10000 * 10000; ++i) {
            long v = System.currentTimeMillis();
        }
        System.out.println("test System.currentTimeMillis(): " + (System.currentTimeMillis() – time));
    }
    static void test2() {
        long time = System.currentTimeMillis();
        for(int i=0; i < 10000 * 10000; ++i) {
            long v = System.nanoTime();
        }
        System.out.println("test System.nanoTime(): " + (System.currentTimeMillis() – time));
    }
}

测试结果

java -server TimeTest
test new Object(): 459
test System.currentTimeMillis(): 3238
test System.nanoTime(): 3178

Comments