java
主页 > 软件编程 > java >

Java使用System.currentTimeMillis()方法计算程序运行时间

2022-03-11 | 秩名 | 点击:

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 类型拼接字符串的耗时情况。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

/**

 * 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 是线程安全的。

原文链接:https://blog.csdn.net/pan_junbiao/article/details/123407263
相关文章
最新更新