在代码开发中,常常需要看代码的执行效率,必须直观的看到某个循环消耗的多少时间,进而针对性的优化,有两种方式。

1.使用System.currentTimeMillis()方法

打印代码开始的执行时间和结束的时间,中间的时间差就是执行耗时。

示例如下:

        long begin = System.currentTimeMillis();
        System.out.println("测试1开始");
        Thread.sleep(300);
        long end = System.currentTimeMillis();
        System.out.println("测试1耗时:"+ String.valueOf(end-begin));

2.使用StopWatch()方法

这个是是spring框架里面的方法,需要引入spring的jar包。

示例如下:

        StopWatch sw = new StopWatch();
        sw.start();
        System.out.println("测试2开始");
        Thread.sleep(500);
        sw.stop();
        System.out.println("测试2耗时:"+sw.getTotalTimeMillis());

 

更多推荐

java打印代码执行耗时