0

I am writing a mini program in Java to use as a stop watch but I am not sure if I am using the right methods in terms of efficiency and accuracy.

From what I have read on stackoverflow it it appears that System.nanoTime() is the best method to use when measuring time elapsed. Is that right? To what extent is it accurate as in to the nearest nanosecond, microsecond, millisecond etc.

Also, while my stop watch is running, I would like it to display the current time elapsed every second. To do this I plan to use a TimerTask and schedule it to report the time (converted to seconds) every second. Is this the best way? Will this have any effect on the accuracy?

Lastly with my current design will this use up much of a computer's resources e.g. processing time.

PS Sorry can't share much code right now cause I've just started designing it. I just did not want to waste time on a design that would be inefficient and make an inaccurate timer.

Saad Attieh
  • 1,396
  • 3
  • 21
  • 42

1 Answers1

2

Yes, you can use java.util.Timer and TimerTask that runs periodically and updates your view every second. However I do not think you have to deal with nono seconds while you actually need resolution of seconds only. Use regular System.currentTimeMillis().

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • That's great thanks. Just to clarify, if I am calculating the time based on when I first call the System.nanoTime() How can I use the System.currentTimeMilis()? Do I also need to make a separate startTime in milliseconds with the System.currentTime()? Thanks again – Saad Attieh Jan 13 '13 at 09:35
  • If I understand your task correctly you just have to create one timer task that knows to update your view. Then create one, global `Timer` and schedule this task to run every second. The task should retrieve current time using for example `System.currentTimeMillis()` and update the view. – AlexR Jan 13 '13 at 09:51
  • 1
    Since nanoseconds is at least as precise as currentTimeMillis, why not use nanoseconds? (*This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().*) – assylias Jan 13 '13 at 09:57