2011-08-23 26 views
10

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

我們只在這裏處理的使用問題,開發問題去[SO]。 –

回答

7

嘗試使用gettimeofday()來測量時間。我已經成功地將它與NDK一起使用,儘管在我的情況下它與pthread_cond_timedwait()一起使用。

2

看到這個參考。 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

我已經用定時器運行了這個版本的代碼,仍然有0秒。這就是爲什麼我使用上面的代碼進行了不同的路線。必須是本地電話和系統時鐘。 – JPM

+0

您是否嘗試過使用Java來測量時間? – Frohnzie

0

檢查睡眠返回代碼(),以確保返回0,這意味着5秒到期。也許在您的環境(模擬器/設備)中,仿生libc的睡眠實現工作不正常。或者嘗試將睡眠秒數增加到60,並在前後添加一些打印語句以確保分鐘發生睡眠。

2

使用函數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; 
}