Java使用System.currentTimeMillis()方法计算程序运行时间的示例代码

 更新时间:2022年3月11日 13:52  点击:287 作者:pan_junbiao

Java 中提供的 System.currentTimeMillis() 方法用于获取当前的计算机时间,时间的表达格式为当前计算机时间和 GMT 时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。

System.currentTimeMillis() 方法的返回类型为 long ,表示毫秒为单位的当前时间。

在开发过程中,通常很多人都习惯使用 new Date() 来获取当前时间。new Date() 所做的事情其实就是调用了 System.currentTimeMillis()方法。如果仅仅是需要或者毫秒数,那么完全可以使用 System.currentTimeMillis() 去代替 new Date(),效率上会高一点。

【示例】计算 String 类型与 StringBuilder 类型拼接字符串的耗时情况。

/**
 * Java使用System.currentTimeMillis()方法计算程序运行时间
 * @author pan_junbiao
 **/
public class CurrentTimeTest
{
    /**
     * 使用String类型拼接字符串耗时
     */
    public static void testString()
    {
        String s = "Hello";
        String s1 = "World";
        long start = System.currentTimeMillis();
        for(int i=0; i<10000; i++)
        {
            s+=s1;
        }
        long end = System.currentTimeMillis();
        long runTime = (end - start);
        System.out.println("使用String类型拼接字符串耗时:" + runTime + "毫秒");
    }
 
    /**
     * 使用StringBuilder类型拼接字符串耗时
     */
    public static void testStringBuilder()
    {
        StringBuilder s = new StringBuilder("Hello");
        String s1 = "World";
        long start = System.currentTimeMillis();
        for(int i=0; i<10000; i++)
        {
            s.append(s1);
        }
        long end = System.currentTimeMillis();
        long runTime = (end - start);
        System.out.println("使用StringBuilder类型拼接字符串耗时:" + runTime + "毫秒");
    }
 
    public static void main(String[] args)
    {
        testString();
        testStringBuilder();
    }
}

运行结果:

 知识点补充:

从上图的运行结果可以看出,在拼接字符串过程中,使用 StringBuilder 对象,而不使用 String 对象。这是因为 String 是不可变的对象,在每一次改变字符串时都会创建一个新的 String 对象;而 StringBuilder 则是可变的字符序列,类似于 String 的字符串缓冲区。所以,在字符串经常修改的地方使用 StringBuilder ,其效率将高于 String。

在这方面运行速度快慢为:StringBuilder > StringBuffer > String。

线程安全上,StringBuilder 是线程不安全的,而 StringBuffer 是线程安全的。

到此这篇关于Java使用System.currentTimeMillis()方法计算程序运行时间的文章就介绍到这了,更多相关Java计算程序运行时间内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/pan_junbiao/article/details/123407263

[!--infotagslink--]

相关文章