android ndk sleep,java – Android NDK定时器

我在c中写了一段代码来计算C代码的一段时间,然后尝试将其回报给

Java代码.但是问题是定时器差动总是回到0.这里是本地C

#include

#include

#include /* sleep() */

#include

#include

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);

}

当我运行这个我总是得到“根据difftime(),睡了-0.00000000秒”.任何想法有什么问题?

——————————–最终代码解决方案————— —————————————–

这是我发现终于不知道为什么我不是一个C大师,但在这里反正.

#include

#include

#include /* sleep() */

#include

#include

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,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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值