How to measure execution time in Java

3 Answers

0 votes
import java.util.concurrent.TimeUnit;

public class MyClass {
    public static void main(String args[]) {
        try {
            long startTime = System.nanoTime();
    
            TimeUnit.SECONDS.sleep(2);
     
            long endTime = System.nanoTime();
     
            long timeElapsed = endTime - startTime;
     
            System.out.println("Execution time in nanoseconds: " + timeElapsed);
            System.out.println("Execution time in milliseconds: " + timeElapsed / 1000000);
        } catch (InterruptedException ie) {
            System.out.println("Error: " + ie);
        }
    }
}



/*
run:

Execution time in nanoseconds: 2000395671
Execution time in milliseconds: 2000

*/

 



answered Mar 13, 2023 by avibootz
edited Mar 13, 2023 by avibootz
0 votes
import java.util.concurrent.TimeUnit;

public class MyClass {
    public static void main(String args[]) {
        try {
            long startTime = System.currentTimeMillis();
 
            TimeUnit.SECONDS.sleep(2);
 
            long endTime = System.currentTimeMillis();
 
            long timeElapsed = endTime - startTime;
     
            System.out.println("Execution time in milliseconds: " + timeElapsed);
        } catch (InterruptedException ie) {
            System.out.println("Error: " + ie);
        }
    }
}



/*
run:

Execution time in milliseconds: 2000

*/

 



answered Mar 13, 2023 by avibootz
0 votes
import java.time.Instant;
import java.util.concurrent.TimeUnit;

public class MyClass {
    public static void main(String args[]) {
        try {
            long startTime = Instant.now().toEpochMilli();
 
            TimeUnit.SECONDS.sleep(2);
 
            long endTime = Instant.now().toEpochMilli();
 
            long timeElapsed = endTime - startTime;
 
            System.out.println("Execution time in milliseconds: " + timeElapsed);
        } catch (InterruptedException ie) {
            System.out.println("Error: " + ie);
        }
    }
}



/*
run:

Execution time in milliseconds: 2000

*/

 



answered Mar 13, 2023 by avibootz

Related questions

2 answers 197 views
2 answers 158 views
2 answers 155 views
1 answer 129 views
1 answer 134 views
1 answer 118 views
...