java 计算代码耗时

 

使用System.currentTimeMillis()函数

1
2
3
long startMs = System.currentTimeMillis();
TimeUnit.SECONDS.sleep(2);
System.out.println("timeCost: " + (System.currentTimeMillis() - startMs));//2001

  

使用System.nanoTime()函数

1
2
3
4
5
long start = System.nanoTime();
TimeUnit.SECONDS.sleep(2);
long finish = System.nanoTime();
long timeElapsed = finish - start;
System.out.println("timeElapsed: " + timeElapsed);//2000132106

  

在java8中使用Instant.now()函数

1
2
3
4
5
Instant start = Instant.now();
TimeUnit.SECONDS.sleep(2);
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis();
System.out.println("timeElapsed: " + timeElapsed);//2001

  

使用apache.commons提供的StopWatch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.apache.commons.lang3.time.StopWatch;
import java.util.concurrent.TimeUnit;
public class StopWatchTest {
    public static void main(String[] args) throws InterruptedException {
        StopWatch started = StopWatch.createStarted();
        TimeUnit.SECONDS.sleep(2);
        started.stop();
        long time = started.getTime();
        long nanoTime = started.getNanoTime();
        long startTime = started.getStartTime();
        System.out.println(time);
        System.out.println(nanoTime);
        System.out.println(startTime);
    }
}

  

使用Spring 框架提供的StopWatch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import com.alibaba.fastjson.JSON;
import org.springframework.util.StopWatch;
import java.util.concurrent.TimeUnit;
public class StopWatchTest {
    public static void main(String[] args) throws InterruptedException {
        StopWatch stopWatch = new StopWatch();
 
        stopWatch.start("function1");
        TimeUnit.SECONDS.sleep(1); // 模拟业务代码
        stopWatch.stop();
 
        stopWatch.start("function2");
        TimeUnit.SECONDS.sleep(1); // 模拟业务代码
        stopWatch.stop();
 
        System.out.println(JSON.toJSONString(stopWatch.getTaskInfo()));
        System.out.println(stopWatch.prettyPrint());
    }
}

  

posted @   草木物语  阅读(454)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示