获取Java代码段运行毫秒数的策略

System.currentTimeMillis()

使用System.currentTimeMillis(),获取系统当前时间(按ms计量),类型为long。

在测试代码段开始前打上第一个时间戳,使用System.currentTimeMillis()获取当前时间;在结束部分再打一个时间戳,再次使用System.currentTimeMillis()获取当前时间。

end-start 即为所求的运行用时。

ms已经很精确了 (Java还有支持ns的API但其实系统未必支持) ,但即使使用ns进行百千万次的运算,也很可能测出耗时0ms,所以想测试就不要去测那种没什么时耗的例子,找点典型的耗时应用算法去做测试。

Test1

我们将简单算术加法进行100W次,结果竟然耗时0ms。

public class GetTimeTest {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        long counter = 0;
        for (int i = 0; i < 1000000; i++) {
            counter += i;
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }
}

测试结果

0

Test2

我们将一个字符串连接100W次(1M次),测一下时间。
哪怕我们只用了空串,然而字符串连接这种行为本身就很消耗时间了,所以必然有个结果。

public class GetTimeTest {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        String str = "";
        for (int i = 0; i < 1000000; i++) {
            str += "";
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }
}

测试结果

47

Test3

我们把Test2的连接次数再翻10倍,达到1000W次:

public class GetTimeTest {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        String str = "";
        for (int i = 0; i < 10000000; i++) {
            str += "";
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }
}

测试结果:

159

总结

打时间戳来测试区间代码段运行时间,可以便于自己开展粗略的性能测试,是很重要的知识,一定要掌握啊!

发布了645 篇原创文章 · 获赞 1334 · 访问量 57万+

猜你喜欢

转载自blog.csdn.net/weixin_43896318/article/details/104633563