2011-09-10 194 views
0

在我的應用程序中,我需要計算每個線程的執行時間[從pthread開始和執行終止開始所花費的時間]。終止可以是'pthread_exit'類型或顯式取消。在下面的代碼中,我使用了pthread specfic數據來保留每個線程的開始時間,因此我可以找到總時間。你們認爲以下方法有意義嗎?如果不是,輸入真的很感激!!!爲了測試目的,線程在睡眠一段時間後自行取消。pthread執行時間?如何計算?

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 

typedef struct _pTime 
{ 
    time_t stime; 
}pTime; 

pthread_key_t kstime; 

void cancelRoutine (void * arg) 
{ 
    pTime etime, *btime; 
    time (&(etime.stime)); 
    printf (" Inside cancelRoutine ...tid: %l \n", pthread_self()); 
    btime = (pTime *) pthread_getspecific (kstime); 
    printf ("Time taken : %lf ", difftime (etime.stime, btime->stime)); 
} 

void * tfunction (void * arg) 
{ 
    int waitTime = (int) arg; 
    printf ("\n Wait Time is %ud ", waitTime); 
    pTime *start; 
    start = (pTime *) malloc (sizeof (pTime)); 
    time (&(start->stime)); 

    pthread_setspecific (kstime, start); 
    pthread_cleanup_push (cancelRoutine, NULL); 
    printf (" Invoking the thread \n"); 
    /* Doing Certain Work here */ 
    sleep (waitTime); 
    pthread_cancel (pthread_self()); 
    sleep(waitTime); 
    pthread_cleanup_pop (NULL); 
} 

int main (int argc, char **argv) 
{ 
    pthread_t tid[2]; 
    int toBeSpend=10, i; 
    pthread_key_create(&kstime, NULL); 

    for (i=0; i<2; i++) 
     pthread_create (&tid[i], NULL, tfunction, (void *)(toBeSpend*(i+1))); 
    sleep (3); 
    for(i=0; i<2; i++) 
     pthread_join (tid[i], NULL); 
} 

回答

0

看來OK,我(雖然我不喜歡特定的線程變量,我寧願用線程信號處理程序捕捉到「取消」,但你的代碼看起來還挺漂亮)

一件事你應該提高是time (&(start->stime));

調用這應該是第一件事該線程函數應該做的(在一個局部變量,然後再複製到malloc分配的ptime),因爲你調用系統在此之前呼叫(需要很多時間,相對性,並且也可以阻止)。

另外,您可能希望使用profiling工具(如gprof)。