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