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 of a method in Java

2 Answers

0 votes
public class MeasureExecutionTimeOfMethod_Java {
    public static long AMethod() {
        long sum = 0;
         
        for (int i = 0; i < 100000; i++) {
            sum += i;
        }
         
        return sum;
    }
     
    public static void main(String[] args) {
        long startTime = System.nanoTime();
 
        long result = AMethod();
 
        long endTime = System.nanoTime();
        long elapsedTime = endTime - startTime;
 
        System.out.println("Execution time in nanoseconds: " + elapsedTime);
        System.out.println("Execution time in milliseconds: " + elapsedTime / 1000000.0);
    }
}

    
    
/*
run:
        
Execution time in nanoseconds: 1170810
Execution time in milliseconds: 1.17081
 
*/

 



answered Nov 16, 2023 by avibootz
edited Aug 4, 2024 by avibootz
0 votes
import java.util.concurrent.TimeUnit;

public class MyClass {
    public static void AMethod() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
    }
    
    public static void main(String[] args) {
        try {
              
            long startTime = System.nanoTime();

            AMethod();

            long endTime = System.nanoTime();
            long elapsedTime = endTime - startTime;

            System.out.println("Execution time in nanoseconds: " + elapsedTime);
            System.out.println("Execution time in milliseconds: " + elapsedTime / 1_000_000);
            System.out.println("Execution time in seconds: " + TimeUnit.SECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS));
 
        } catch (InterruptedException ie) {
            System.out.println(ie);
        }
    }
}
   
   
   
   
   
/*
run:
       
Execution time in nanoseconds: 2000636786
Execution time in milliseconds: 2000
Execution time in seconds: 2

*/

 



answered Nov 16, 2023 by avibootz

Related questions

1 answer 123 views
1 answer 105 views
1 answer 107 views
3 answers 215 views
215 views asked Mar 13, 2023 by avibootz
2 answers 138 views
2 answers 131 views
...