How to find time taken to run a Java program?

后端 未结 7 1851
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 06:17

I have a Java application that I\'ve been working on and I just realized that the program has to return a value in less than a minute, but don\'t know how to find or display

相关标签:
7条回答
  • 2020-12-24 06:59

    You can use 2 APIs provided by System class

    1. System.currentTimeMillis() If code takes time in Millisecond range
    2. System.nanoTime() If code takes time in Nanosecond range

    Sample Code

    public class TestTimeTaken {
        public static void main(String args[]) throws InterruptedException{
            long startTimeNanoSecond = System.nanoTime();
            long startTimeMilliSecond = System.currentTimeMillis();
    
            //code
            Thread.sleep(1000);
            //code
    
            long endTimeNanoSecond = System.nanoTime();
            long endTimeMilliSecond = System.currentTimeMillis();
    
            System.out.println("Time Taken in "+(endTimeNanoSecond - startTimeNanoSecond) + " ns");
            System.out.println("Time Taken in "+(endTimeMilliSecond - startTimeMilliSecond) + " ms");
    
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题