JPM*_*JPM 10 c java java-native-interface android android-ndk
我在c中编写了一段代码来计算C代码的一部分所花费的时间,然后尝试将其报告回Java代码.但问题是定时器差分总是回零.这是原生C
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* sleep() */
#include <time.h>
#include <jni.h>
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)->NewStringUTF(env, buf);
}
Run Code Online (Sandbox Code Playgroud)
当我运行这个时,我总是得到"根据difftime(),睡了-0.00000000秒".有什么想法有什么不对吗?
-------------------------------- 最终代码解决方案 --------------- -----------------------------------------
这是我发现最终工作不确定为什么因为我不是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);
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11869 次 |
| 最近记录: |