java Android NDK 计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7165863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:55:42  来源:igfitidea点击:

Android NDK timers

javaandroidcjava-native-interfaceandroid-ndk

提问by JPM

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

我用 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);
}

When I run this I always get "according to difftime(), slept for -0.00000000 seconds". Any ideas what's wrong?

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

--------------------------------Final Code Solution--------------------------------------------------------

--------------------------------最终代码解决方案--------------- -----------------------------------------

This is what I found finally works not sure why as I am not a C guru but here it is anyway.

这就是我发现最终有效的方法,不知道为什么,因为我不是 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);
}

Java code for android looks like this:

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

采纳答案by Joel F

Try using gettimeofday()to measure time. I have successfully used it with the NDK, although in my case it was with pthread_cond_timedwait().

尝试使用gettimeofday()来测量时间。我已经成功地将它与 NDK 一起使用,尽管在我的情况下它与pthread_cond_timedwait().

回答by Sergey K.

Use gettimeofday() like this:

像这样使用 gettimeofday():

bool QueryPerformanceCounter( int64_t* performance_count )
{
    struct timeval Time;

    /* Grab the current time. */
    gettimeofday( &Time, NULL );
    *performance_count = Time.tv_usec + /* Microseconds. */
                         Time.tv_sec * usec_per_sec; /* Seconds. */

    return true;
}

回答by Frohnzie

See this reference. http://www.cplusplus.com/reference/clibrary/ctime/difftime/

请参阅此参考。 http://www.cplusplus.com/reference/clibrary/ctime/difftime/

/* difftime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t start,end;
  char szInput [256];
  double dif;

  time (&start);
  printf ("Please, enter your name: ");
  gets (szInput);
  time (&end);
  dif = difftime (end,start);
  printf ("Hi %s.\n", szInput);
  printf ("It took you %.2lf seconds to type your name.\n", dif );

  return 0;
}

回答by uperez

Check the return code for sleep() to ensure that 0 is returned, meaning the 5 seconds have expired. Maybe the bionic libc implementation of sleep is not working properly in your environment (emulator/device). Or try and increase the number of seconds to sleep to 60 and add some print statements before and after to ensure that the minute is sleep occurs.

检查 sleep() 的返回码以确保返回 0,这意味着 5 秒已过期。也许 sleep 的仿生 libc 实现在您的环境(模拟器/设备)中无法正常工作。或者尝试将睡眠秒数增加到 60 并在前后添加一些打印语句以确保分钟是睡眠发生。