How to measure time elapsed in Java

2 Answers

0 votes
import java.util.concurrent.TimeUnit;
  
public class MeasureTimeElapsed_Java {
    public static void main(String args[]) throws InterruptedException {
        long startTime = System.currentTimeMillis();
    
        // code to be measured 
        TimeUnit.SECONDS.sleep(2);
        // code to be measured 
          
        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
  
        System.out.println("Elapsed time in milliseconds: " + elapsedTime);
    }
}
   
   
   
   
/*
run:
   
Elapsed time in milliseconds: 2000
   
*/

 



answered Oct 14, 2023 by avibootz
edited Aug 4, 2024 by avibootz
0 votes
import java.util.concurrent.TimeUnit;
import java.time.Duration;
import java.time.Instant;

public class MyClass {
    public static void main(String args[]) throws InterruptedException {
        Instant start = Instant.now();
  
        // code to be measured 
        TimeUnit.SECONDS.sleep(2);
        // code to be measured 
        
        Instant end = Instant.now();
        Duration elapsed = Duration.between(start, end);
        
        System.out.println("Elapsed time in milliseconds: " + elapsed.toMillis());
    }
}
 
 
 
 
/*
run:
 
Elapsed time in milliseconds: 2000
 
*/

 



answered Oct 14, 2023 by avibootz

Related questions

1 answer 97 views
97 views asked Oct 17, 2024 by avibootz
1 answer 107 views
107 views asked Aug 4, 2024 by avibootz
1 answer 109 views
109 views asked Aug 4, 2024 by avibootz
2 answers 217 views
3 answers 249 views
249 views asked Mar 13, 2023 by avibootz
...