(3/20/13 11:14 AM), naruse (Yui NARUSE) wrote:
> 
> Issue #8096 has been updated by naruse (Yui NARUSE).
> 
> 
> Eregon (Benoit Daloze) wrote:
>> On 19 March 2013 17:56, headius (Charles Nutter) <headius / headius.com> wrote:
>>  >
>>  > Issue #8096 has been updated by headius (Charles Nutter).
>>  >
>>  >
>>  > A few more thoughts to keep this alive...
>>  >
>>  > Implementation in JRuby:
>>  >
>>  > def Time.timestamp
>>  >   java.lang.System.nano_time / 1000
>>  > end
>>  
>>  That seems to work on Linux and some others, but what about Windows?
>>  It likely happens to be clock_gettime() or such in UNIX.
> 
> Python summarized those time related functions:
> http://www.python.org/dev/peps/pep-0418/
> 
>>  The doc says "This method can only be used to measure elapsed time and
>>  is not related to any other notion of system or wall-clock time."
>>  
>>  http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime%28%29
> 
> Whether wall-clock or monotonic clock is desired is the most important point.

FYI: This is the actual OpenJDK System.nanoTime implementation.
Moreover, JVM know what nanoTime is and it can bypass normal method invocation overhead.

-----------------------------------------
jlong os::javaTimeNanos() {
  if (Linux::supports_monotonic_clock()) {
    struct timespec tp;
    int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp);
    assert(status == 0, "gettime error");
    jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
    return result;
  } else {
    timeval time;
    int status = gettimeofday(&time, NULL);
    assert(status != -1, "linux error");
    jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
    return 1000 * usecs;
  }
}
------------------------------------------

However this is one naive point. almost all programmer think following code makes
_always_ positive.

t0 = System.nanoTime()
...
t1 = System.nanoTime()
t = t1 - t0

however this is not correct when following reasons.

- some os don't support monotonic.
- x86 has silly tsc implementation and time run backward when multiple cpus
  even if using monotonic.
  i.e. tsc time depend on individual cpus and os scheduler migrate process
       across cpus transparency. that's intel silly.


That says, System.nanoTime encourage bad programming. but it works excellent when
we can ignore disadvantages.