【问题标题】:Interpreting time command output on a multi threaded program在多线程程序上解释时间命令输出
【发布时间】:2013-07-16 02:10:09
【问题描述】:

我有一个多线程程序,我在所有 pthread_create 之前和所有 pthread_join 之后开始分析时间。

现在我发现这一次,我们称之为X,如下图"Done in xms"其实是user + sys time of time 输出。在我的应用程序中,a.out 的 number 参数控制要生成的线程数。 ./a.out 1 产生 1 个 pthread 并且 ./a.out 2 产生 2 个线程,其中每个线程做同样多的工作。

我期待 X 是实时而不是用户 + 系统时间。有人可以告诉我为什么不是这样吗?那么这真的意味着我的应用程序确实在并行运行,线程之间没有任何锁定。

[jithin@whatsoeverclever tests]$ time ./a.out 1
Done in 320ms

real    0m0.347s
user    0m0.300s
sys     0m0.046s
[jithin@whatsoeverclever tests]$ time ./a.out 2
Done in 450ms

real    0m0.266s
user    0m0.383s
sys     0m0.087s
[jithin@whatsoeverclever tests]$ time ./a.out 3
Done in 630ms

real    0m0.310s
user    0m0.532s
sys     0m0.105s

代码

int main(int argc, char **argv) {

  //Read the words
  getWords();

  //Set number of words to use
  int maxWords = words.size();
  if(argc > 1) {
     int numWords = atoi(argv[1]);
     if(numWords > 0 && numWords < maxWords) maxWords = numWords;
  }

  //Init model
  model = new Model(MODEL_PATH);
  pthread_t *threads = new pthread_t[maxWords];
  pthread_attr_t attr;
  void *status;

  // Initialize and set thread joinable
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  int rc;
clock_t startTime = clock();

  for(unsigned i=0; i<maxWords; i++) {
     //create thread
     rc = pthread_create(&threads[i], NULL, processWord, (void *)&words[i] );
     if (rc){
         cout << "Error:unable to create thread: " << i << "," << rc << endl;
         exit(-1);
      }
  }

  // free attribute and wait for the other threads
  pthread_attr_destroy(&attr);
  for(unsigned i=0; i<maxWords; i++) {
     rc = pthread_join(threads[i], &status);
     if (rc){
         cout << "Error:unable to join thread: " << i << "," << rc << endl;
         exit(-1);
      }
  }

  clock_t endTime = clock();

  float diff = (((float)endTime - (float)startTime) / 1000000.0F ) * 1000;
  cout<<"Done in "<< diff << "ms\n";
  delete[] threads;
  delete model;
}

【问题讨论】:

  • 向我们展示您的代码,以便我们了解它是如何获得这些数字的。也许您正在调用clock,它专门用于返回进程使用的处理器时间。
  • @DavidSchwartz 我已经添加了我的主程序。是的,我正在调用时钟()。我的错。
  • @DavidSchwartz 如果您可以将其添加为答案,我可以接受。

标签: linux multithreading time pthreads


【解决方案1】:

clock 函数专门用于返回进程使用的处理器时间。如果你想测量墙上的时间,这不是正确的功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多