0

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

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

1 回答 1

1

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

于 2013-07-17T19:41:55.420 回答