Search code examples
javamultithreadingtimerdelaycountdowntimer

How to use a Timer without a delay?


I know that:

Thread.sleep(1000)

means delay for exactly one second before executing the code, but it there a way to use a timer to just count the time that past when the program executes without delaying the program? Thanks.


Solution

  • Keep the current time in a variable

    long oldTime = System.nanoTime();
    

    At the end of your program, print the current time - the old time and that will be the execution time in nano seconds.

    System.out.println((System.nanoTime() - oldTime));