title: Android NDK timers
body: <p>I wrote a piece of code in c to calculate how long a section of the C code was taking, then trying to report it back to the Java code.  But the problem is that the timer differential always comes back as zero.  here is the native C</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt; /* sleep() */
  #include &lt;time.h&gt;
  #include &lt;jni.h&gt;
  
  jstring Java_com_nsf_ndkfoo_NDKFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
  
      time_t start, end;
  
      start = time(NULL);
      if(start == (time_t)-1) {
        return 1;
      }
  
      sleep(5);
  
      end = time(NULL);
  
      char buf[60] = { 0 };
  
      sprintf(buf,"according to difftime(), slept for %.8f seconds\n", (int)difftime(end, start));
  
      return (*env)-&gt;NewStringUTF(env, buf);
  }
  </code></pre>
  
  <p>When I run this I always get "according to difftime(), slept for -0.00000000 seconds".  Any ideas what's wrong?</p>
  
  <p>--------------------------------<strong>Final Code Solution</strong>--------------------------------------------------------</p>
  
  <p>This is what I found finally works not sure why as I am not a C guru but here it is anyway.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt; /* sleep() */
  #include &lt;sys/time.h&gt;
  #include &lt;jni.h&gt;
  
  jstring Java_com_nsf_ndkfoo_NDKFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
  
      struct timeval start;
      struct timeval end;
  
      gettimeofday(&amp;start, NULL);
      sleep(5);
  
      gettimeofday(&amp;end, NULL);
  
      char buf[60] = { 0 };
  
      sprintf(buf,"according to difftime(), slept for %ld seconds\n",  ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)));
  
      return (*env)-&gt;NewStringUTF(env, buf);
  }
  </code></pre>
  
  <p>Java code for android looks like this:</p>
  
  <pre><code>package com.nsf.ndkfoo;
  
  import android.app.Activity;
  import android.app.AlertDialog;
  import android.os.Bundle;
  
  public class NDKFooActivity extends Activity {
      // load the library - name matches jni/Android.mk
      static {
          System.loadLibrary("ndkfoo");
      }
  
      // declare the native code function - must match ndkfoo.c
      private native String invokeNativeFunction();
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
  
          // this is where we call the native code
          String hello = invokeNativeFunction();
  
          new AlertDialog.Builder(this).setMessage(hello).show();
      }
  }
  </code></pre>