2011-08-23 12 views
10

Escribí un fragmento de código en c para calcular cuánto tiempo estaba tomando una sección del código C, y luego intenté informarlo al código Java. Pero el problema es que el diferencial del temporizador siempre regresa como cero. aquí está el nativo de CAndroid NDK temporizadores

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

Cuando ejecuto esto siempre me dan "según difftime(), durmió durante -0.00000000 segundos". Alguna idea de lo que está mal?

-------------------------------- Solución de código final --------- -----------------------------------------------

Esto es lo que encontré, finalmente funciona, no estoy seguro de por qué, ya que no soy un gurú de C, pero aquí está de todos modos.

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

código Java para las miradas Android como esto:

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

Sólo manejar las preguntas de uso aquí, preguntas dev seguir [SO]. –

Respuesta

7

Intente utilizar gettimeofday() para medir el tiempo. Lo utilicé con éxito con el NDK, aunque en mi caso fue con pthread_cond_timedwait().

2

Ver esta referencia. 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; 
} 
+0

Ya ejecuté esta versión del código usando temporizadores y todavía tengo 0 segundos. Es por eso que tomé una ruta diferente con el código anterior. Debe ser algo con llamadas nativas y reloj del sistema. – JPM

+0

¿Has intentado usar Java para medir la hora? – Frohnzie

0

Compruebe el código de retorno para el sueño() para garantizar que se devuelve 0, es decir, los 5 segundos han expirado. Quizás la implementación de la libra biónica del sueño no esté funcionando correctamente en su entorno (emulador/dispositivo). O intente aumentar el número de segundos para dormir a 60 y agregue algunas instrucciones de impresión antes y después para asegurarse de que el minuto se duerma.

2

Uso gettimeofday() así:

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