我在c中編寫了一段代碼來計算一段C代碼所花費的時間,然後嘗試將其報告回Java代碼。但問題是定時器差分總是回到零。這裏是本機C當我運行這個時,我總是得到「根據difftime(),睡了-0.00000000秒」。任何想法有什麼不對?Android NDK定時器
-------------------------------- Final Code Solution --------- -----------------------------------------------
這是我終於找到的作品不知道爲什麼,因爲我不是C大師,但在這裏它是無論如何。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* sleep() */
#include <sys/time.h>
#include <jni.h>
jstring Java_com_nsf_ndkfoo_NDKFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
struct timeval start;
struct timeval end;
gettimeofday(&start, NULL);
sleep(5);
gettimeofday(&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)->NewStringUTF(env, buf);
}
的Android看起來像這樣的Java代碼:
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();
}
}
我們只在這裏處理的使用問題,開發問題去[SO]。 –