0

Here is my modest proposal:

  1. When the JVM starts
    1. Call System.currentTimeMillis() and store as starting "wall clock" time:
      long currentTimeMillis0.
    2. Call System.nanoTime() and store as starting "nano" time:
      long nanoTime0.
  2. Throughout the run of the program, store many timestamps using System.nanoTime().

I am well aware the exact value of a nanoTime is useless by itself, but useful when used in the context of a duration: endNanoTime - beginNanoTime.

Is it then reasonable, at any nanoTime recorded, to calculate "currentTimeNanos" as:
(1000L * currentTimeMillis0) + (anyNanoTime - nanoTime0)?

kevinarpe
  • 20,319
  • 26
  • 127
  • 154

2 Answers2

1

I think you need to combine start/end times, both in millis and nano. For example:

long startTimeMillis = System.currentTimeMillis() * 1000;
long startTimeNano = System.nanoTime();
... // do some work
long currentTimeNano = (System.currentTimeMillis()*1000 - startTimeMillis) + (System.nanoTime() - startTimeNano);

For more information, the official javadoc of the nanoTime method: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#nanoTime()

Alejandro Goñi
  • 532
  • 1
  • 3
  • 14
  • 1
    It appears to be a complicated way to calculate the nano-time difference plus 0.1% with a slight error. Can you explain how this is better than nano time alone? – Peter Lawrey Jan 10 '16 at 16:13
  • The scale between milli and nano is 1000000 not 1000. But in Java you can't do anything useful with sub-milli instant (as opposed to duration) anyway. – dave_thompson_085 Jan 10 '16 at 17:52
1

Where I use milli-second and nano-time is I use nano-time for calculating small differences in time and a milli-second timer once at the start to give context.

Note: it is possible to use nano-time between machine if you have a continuous stream of timings. i.e. you can estimate the best timings between them and detect outliers (even if you don't know the absolute difference) I use this class to help estimate the RunningMinimum

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130