1

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.

1 Answers1

1

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));
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • 1
    Also, `System..currentTimeMillis()` is limited to the precision of the system clock, usually around `15ms`. `nanoTime` is always a better choice for timing events. Although, obviously any benchmark using this naive approach will be deeply flawed in any case. – Boris the Spider Apr 18 '15 at 16:51
  • Well, keyboard input at best is 30 ms, right? so shouldn't 15ms be more than enough? –  Apr 18 '15 at 16:54
  • @Jean-FrançoisSavard good answer anyway. –  Apr 18 '15 at 16:58