Skip to content

Instantly share code, notes, and snippets.

@yptheangel
Created September 1, 2019 10:40
Show Gist options
  • Save yptheangel/fc0178480c50a99c1209b2f60bb712a2 to your computer and use it in GitHub Desktop.
Save yptheangel/fc0178480c50a99c1209b2f60bb712a2 to your computer and use it in GitHub Desktop.
Use a timer to count the time to complete a function in Java
import java.util.concurrent.TimeUnit;
public class JavaTimer{
public static void main(String []args){
long start_time =System.nanoTime();
//Create a delay of 1 second or 1000milliseconds
try{
Thread.sleep(1000);
}catch (InterruptedException e){
System.out.println(e);}
long end_time = System.nanoTime();
long elapsed_time_in_nanoseconds = end_time - start_time;
long elapsed_time_in_s = TimeUnit.SECONDS.convert(elapsed_time_in_nanoseconds, TimeUnit.NANOSECONDS);
System.out.println("Elapsed time: "+elapsed_time_in_s+"second(s)");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment