3

I am trying to measure time in JNI call, it call from native to Java.

In C code, I apply "GetTickCount" api to get JNI execution time and "System.nano" in Java.

Example:

long start = GetTickCount();
....//CallStaticMethod exampleMethod...
long end = GetTickCount();
long duration = end - start;

And in Java

public static exampleMethod(){
    long start = System.nano();
    //do something
    long end = System.nano();
    long duration = TimeUnit.NANOSECONDS.toMilis(end - start);
}

Sometimes, it is inconsistent because the java's duration is more than C's duration. ( about 5 to 10 miliseconds)

LGProgramer
  • 45
  • 1
  • 6
  • `GetTickCount` returns **milli**seconds, `System.nanoTime()` returns **nano**seconds. – apangin Mar 21 '16 at 09:51
  • Sorry for inconvenience. It's not related to unit time. I miss the last line code while I post here. Actually, I convert nano to miliseconds in my source code :). Java's duration is more than C's duration as the same unit ( miliseconds) – LGProgramer Mar 21 '16 at 12:52

2 Answers2

2

GetTickCount and System.nanoTime() use different time sources.

The problem with GetTickCount is its very poor resolution, usually around 10ms. This is explicitly remarked in the documentation:

The resolution of the GetTickCount function is limited to the resolution of the system timer, which is typically in the range of 10 milliseconds to 16 milliseconds.

No wonder that it can differ from nanoTime that much.

To make measurements consistent with System.nanoTime, use higher resolution timer by calling either QueryPerformanceCounter or GetSystemTimeAsFileTime.

EDIT

JDK's System.nanoTime() is implemented on top of QueryPerformanceCounter (the source).

apangin
  • 92,924
  • 10
  • 193
  • 247
0

On the java side of things you will always be at the mercy of the JVM :

http://shipilev.net/blog/2014/nanotrusting-nanotime/