• java 计算代码耗时


     

    使用System.currentTimeMillis()函数

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

      

    使用System.nanoTime()函数

    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()函数

    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

    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

    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());
        }
    }
    

      

  • 相关阅读:
    据说,能找出15个以上的的视力才正常....
    看看用PS来转基因的动物,居然很欢乐!!
    《天引》读书笔记——由新月形面积引发的人类长达2000年的探索。
    练习使用策略模式
    折半查找
    UltraEdit常用配置&搭建Java/C开发环境
    一个操作系统的实现_十分钟完成的操作系统——到这里博客迁移工作圆满结束
    C++中的变量初始化
    LeetCode Range Sum Query
    Peeking Iterator
  • 原文地址:https://www.cnblogs.com/ooo0/p/16189865.html
Copyright © 2020-2023  润新知