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