如何测量每个线程的时间用C? [英] How do I measure time per thread in C?

查看:225
本文介绍了如何测量每个线程的时间用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个code与线程有多个号码和我想打印花了我完成我的任务分配给第i个线程来完成的时间。这意味着我要打印每个线程花时间要与DoSomething的函数来完成

I am working on a code with multiple number of threads and I want to print the time it took for me to complete task I assigned the i-th thread to do. Meaning I want to print the time each thread took to be done with the doSomeThing function

int main(int argc, char *argv[]){
   // ...
         i=0;
         while (i < NumberOfThreads){

              check = pthread_create(&(id_arr[i]), NULL, &doSomeThing, &data);

              i++;
         }
   // ...
}

void* doSomeThing(void *arg){
   // ...
}

如果我想补充函数gettimeofday(安培; thread_start,NULL)在pthread_create ,然后添加函数gettimeofday(安培; thread_end,NULL)在pthread_create ,我是否会实际测量只是时间每个线程花时间或主拿?如果我把 gettimeofday的中的 DoSomething的函数不会他们创造比赛条件?

if I add gettimeofday(&thread_start, NULL) before the pthread_create and then add gettimeofday(&thread_end, NULL) after the pthread_create, will I be actually measuring the time each thread took or just the time the main took? And if I put the gettimeofday inside the doSomething function wouldn't they create race-conditions?

如果您有关于如何衡量每个线程的时候,请让我知道,谢谢你的想法。

If you have any idea on how to measure the time per thread please let me know, thank you.

推荐答案

您当然可以使用 gettimeofday的线程函数本身内部。使用本地(栈)变量是完全线程安全的 - 每个线程有自己的堆栈(定义)运行

You can certainly use gettimeofday inside the thread function itself. Using local (stack) variables is completely thread-safe - every thread runs on its own stack (by definition).

void* doSomeThing(void *arg){
    struct timeval t0, t1, dt;

    gettimeofday(&t0, NULL);

    // do work

    gettimeofday(&t1, NULL);

    timersub(&t1, &t0, &dt);

    fprintf(stderr, "doSomeThing (thread %ld) took %d.%06d sec\n",
               (long)pthread_self(), dt.tv_sec, dt.tv_usec);
}

如果你把同样的code左右在pthread_create(),你只会看到花费的时间为线程是的创建的金额的,不执行。如果在pthread_create 阻止,直到线程完成,就没有任何意义了以往使用线程!

If you put the same code around pthread_create(), you would only see the amount of time it took for the thread to be created, not executed. If pthread_create blocked until the thread completed, there would be no point in ever using threads!

这篇关于如何测量每个线程的时间用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆