【问题标题】:pthread execution time ? How to calculate?pthread 执行时间?如何计算?
【发布时间】:2011-09-10 08:31:39
【问题描述】:

在我的应用程序中,我需要计算每个线程的执行时间 [字面意思是它从 pthread 启动到执行终止所花费的时间]。终止可以是“pthread_exit”类型或显式取消。在下面的代码中,我使用了 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);
}

【问题讨论】:

    标签: c linux pthreads


    【解决方案1】:

    对我来说似乎没问题(虽然我不喜欢特定的线程变量,但我宁愿使用线程信号处理程序来捕获“取消”,尽管你的代码看起来有点漂亮)

    你应该改进的一件事是time (&amp;(start-&gt;stime));的调用

    这应该是线程函数应该做的第一件事(首先在本地 var 上,然后将其复制到 malloc'ed pTime),因为您在此之前调用系统调用(需要很多时间,相对论,还可以阻塞)。

    另外,您可能希望使用分析工具(例如 gprof)进行调整。

    【讨论】:

      猜你喜欢
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 2018-01-28
      • 2021-06-21
      相关资源
      最近更新 更多