Determine the user and system time used by the stream

We have a qthreads-based workflow mechanism where worker threads collect input packets when they are queued and then put their output in another queue for other workflows to start the next step; etc. until the entire input has been consumed and the entire output has been generated.

Typically, multiple threads will perform the same task, while others will simultaneously run other tasks. We want to evaluate the performance of these multi-threaded tasks in order to direct optimization efforts.

It is easy to get the real (elapsed) time that a given thread executing a task has received. We just look at the difference between the return values โ€‹โ€‹of the POSIX times () function at the beginning and end of the run () thread procedure. However, I cannot figure out how to get the appropriate user and system time. Getting this data from struct tmswhich you pass in times () does not work, because this structure gives the total number of users and systems for all threads running during the current thread.

+3
source share
1 answer

, Linux, getrusage() RUSAGE_THREAD? Solaris RUSAGE_LWP, , , , , POSIX- .

:

#define _GNU_SOURCE
#include <sys/time.h>
#include <sys/resource.h>
#include <stdio.h>
#include <pthread.h>
#include <assert.h>
#include <unistd.h>

struct tinfo {
  pthread_t thread;     
  int id;
  struct rusage start;
  struct rusage end;
};

static void *
thread_start(void *arg)
{
  struct tinfo *inf = arg;
  getrusage(RUSAGE_THREAD, &inf->start);
  if (inf->id) {
     sleep(10);
  }
  else {
     const time_t start = time(NULL);
     while (time(NULL) - start < 10); // Waste CPU time!
  }
  getrusage(RUSAGE_THREAD, &inf->end);
  return 0;
}

int main() {
  static const int nrthr = 2;
  struct tinfo status[nrthr];
  for (int i = 0; i < nrthr; ++i) {
     status[i].id = i;
     const int s = pthread_create(&status[i].thread, 
                                            NULL, &thread_start, 
                                            &status[i]);
     assert(!s);
  }

  for (int i = 0; i < nrthr; ++i) {
     const int s = pthread_join(status[i].thread, NULL);
     assert(!s);
     // Sub-second timing is available too
     printf("Thread %d done: %ld (s) user, %ld (s) system\n", status[i].id, 
              status[i].end.ru_utime.tv_sec - status[i].start.ru_utime.tv_sec, 
              status[i].end.ru_stime.tv_sec - status[i].start.ru_stime.tv_sec);
  }  
}

, - , GetProcessTimes()

+1

Source: https://habr.com/ru/post/1757882/


All Articles