2011-09-10 19 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));

の呼び出しである(最初のローカルVARにして、mallocさPTIMEにコピー)を使用すると、システムを呼び出しているので、それ以前に呼び出す(時間がかかり、相対性理論をとり、ブロックすることもできます)。

また、gprofなどのプロファイリングツールを使用することもできます。

関連する問題