解释多线程程序上的时间命令输出

时间:2013-07-17 13:34:27

标签: linux multithreading time pthreads

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

现在我发现这次,我们称之为 X ,如下所示“Done in xms”实际上是时间的用户+系统时间输出。在我的应用程序中,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;
}

1 个答案:

答案 0 :(得分:1)

具体记录了clock函数,以返回进程使用的处理器时间。如果你想测量经过的墙壁时间,那就不是正确的功能了。