0

At least on my Linux computer, changing the time of the system affects System.nanoTime(), making it unreliable to determine an interval if the time of the system is changed during that interval.

Is there an equivalent to this function which do not depend on the time of the system?

Winter
  • 3,894
  • 7
  • 24
  • 56
  • Does *changing time* refer to changing the timezone or the actual time? – Matt Jul 17 '21 at 04:07
  • Changing the actual time, not the timezone. Changing the timezone has no effect on `System.nanoTime()` on my system. Ideally it should be independent of any such system changes though – Winter Jul 17 '21 at 04:10
  • 3
    I think the answer is No. Where possible, nanoTime uses a monotonic clock, but it is not always possible. (It depends on what the OS provides.) See https://stackoverflow.com/questions/1937619 – Stephen C Jul 17 '21 at 04:17
  • So if you absolutely require to measure time in a way that is immune to system time adjustments, **turn off adjustments**. For example if your OS uses `systemd`, stop the `ntp.service`. – Stephen C Jul 17 '21 at 04:20
  • If you cannot rely on the computers own clock, then you need to use an external time source. There are many time servers out there providing a web service API, so good luck researching them to find which one best fits your need. – Andreas Jul 17 '21 at 04:46
  • I have never tried this, but perhaps a cheap USB GPS dongle could provide an independent time source. – tgdavies Jul 17 '21 at 04:50
  • Unfortunately, many operating systems do not distinguish between the concepts of "what time is it?" and "how much time has actually elapsed?". For the latter, you'd want a counter that incremented uniformly as long as the system was up, independent of the former. System.nanoTime() is not what you might want, but it's what we're stuck with. – iggy Jul 17 '21 at 13:37

0 Answers0