2011-09-10 193 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)。