c - pthread执行时间?如何计算?

标签 c linux pthreads

在我的应用程序中,我需要计算每个线程的执行时间[字面意思是从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);
}

最佳答案

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

您应该改进的一件事是调用 time (&(start->stime));

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

此外,您可能需要使用分析工具(例如 gprof)进行配置。

关于c - pthread执行时间?如何计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7370562/

相关文章:

c - 从 TCP/IP 流量构建文件?

linux - 如何在系统级别将目录添加到 Perl 库路径?

linux - 从源代码构建软件并将其安装在 Linux 上的自定义文件夹中

c++ - 在许多不同的平台上使用 c/c++ 中的线程

c++ - 在线程争用情况下等待的最快方法

python - 将 C 的 fread(&struct,....) 移植到 Python

c - 程序中同时使用puts()、gets()、getchar()、putchar()函数

c - 整数到字节数组 Little Endian,反之亦然

python - Raspberry Pi BeautifulSoup 库不工作

cuda - 如何将静态数据分区到多个 GPU 中?