'showtimes'에 해당되는 글 1건

  1. 2011.09.03 showtimes - exit핸들러 등록하여 프로그램 CPU 사용률 출력
2011. 9. 3. 02:32

Catexit 함수는 사용자가 정의한 종료 핸들러를 등록한다.

종료 핸들러는 프로그램이 main 함수로부터 리턴 하거나 exit 함수를 호출하였을 때

마지막에 등록된 핸들러가 먼저 실행되는 순서로 실행. (여러 번 호출하여 핸들러 등록 가능)

 

 

showtimes 예제는 showtimes 함수를 exit 핸들러로 등록하여

프로그램과 그 자식들이 사용한 시간에 대한 통계를 표준 에러로 출력한다.

 

[ 예제 코드 : showtimes.c ]

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/times.h>
#include <sys/wait.h>

int wastetime(int maxus);

static void showtimes(void) {
   double ticks;
   struct tms tinfo;

   if ((ticks = (double) sysconf(_SC_CLK_TCK)) == -1)
      perror("Failed to determine clock ticks per second");
   else if (times(&tinfo) == (clock_t)-1)
      perror("Failed to get times information");
   else {
      fprintf(stderr, "User time:              %8.3f seconds\n",
         tinfo.tms_utime/ticks);
      fprintf(stderr, "System time:            %8.3f seconds\n",
         tinfo.tms_stime/ticks);
      fprintf(stderr, "Children's user time:   %8.3f seconds\n",
         tinfo.tms_cutime/ticks);
      fprintf(stderr, "Children's system time: %8.3f seconds\n",
         tinfo.tms_cstime/ticks);
   }
}
 
int main(void) {
   if (atexit(showtimes))  {
      fprintf(stderr, "Failed to install showtimes exit handler\n");
      return 1; 
   }
   if (fork())
      wastetime(2900000);
   else
      wastetime(5400000);
   if (wait(NULL) > 0)
      fprintf(stderr, "\nChild has exited, parent stats follow:\n");
   return 0;
}

times 함수는 시간 틱(tick) 수의 시간 정보를 나타낸다.

 

 

[ 예제 코드 : wastetime.c ]

#include <stdio.h>
#include <sys/time.h>
#define MILLION 1000000L

/* waste maxus microseconds of time */
int wastetime(int maxus) {
   long timedif;
   struct timeval tp1, tp2;

   if (gettimeofday(&tp1, NULL)) {
      fprintf(stderr, "Failed to get initial time\n");
      return 1;
   }
   timedif = 0;
   while (timedif < maxus) {
      if (gettimeofday(&tp2, NULL)) {
         fprintf(stderr, "Failed to get check time\n");
         return 1;
      }
      timedif = MILLION*(tp2.tv_sec - tp1.tv_sec) +
                   tp2.tv_usec - tp1.tv_usec;
      if (timedif < 0)
         break;
   }
   return 0;
}

 

▶ 사용 예:

$ ./showtimes

User time:                         1.270 seconds

System time:                    2.660 seconds

Children's user time:      0.000 seconds

Children's system time: 0.000 seconds

 

Child has exited, parent stats follow:

User time:                        0.460 seconds

System time:                    0.970 seconds

Children's user time:      1.270 seconds

Children's system time: 2.660 seconds

 

Posted by devanix