Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

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 175 views
2 answers 138 views
2 answers 131 views
1 answer 116 views
1 answer 123 views
1 answer 105 views
...