Header And Logo

PostgreSQL
| The world's most advanced open source database.

pg_rusage.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * pg_rusage.c
00004  *    Resource usage measurement support routines.
00005  *
00006  *
00007  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
00008  * Portions Copyright (c) 1994, Regents of the University of California
00009  *
00010  *
00011  * IDENTIFICATION
00012  *    src/backend/utils/misc/pg_rusage.c
00013  *
00014  *-------------------------------------------------------------------------
00015  */
00016 #include "postgres.h"
00017 
00018 #include <unistd.h>
00019 
00020 #include "utils/pg_rusage.h"
00021 
00022 
00023 /*
00024  * Initialize usage snapshot.
00025  */
00026 void
00027 pg_rusage_init(PGRUsage *ru0)
00028 {
00029     getrusage(RUSAGE_SELF, &ru0->ru);
00030     gettimeofday(&ru0->tv, NULL);
00031 }
00032 
00033 /*
00034  * Compute elapsed time since ru0 usage snapshot, and format into
00035  * a displayable string.  Result is in a static string, which is
00036  * tacky, but no one ever claimed that the Postgres backend is
00037  * threadable...
00038  */
00039 const char *
00040 pg_rusage_show(const PGRUsage *ru0)
00041 {
00042     static char result[100];
00043     PGRUsage    ru1;
00044 
00045     pg_rusage_init(&ru1);
00046 
00047     if (ru1.tv.tv_usec < ru0->tv.tv_usec)
00048     {
00049         ru1.tv.tv_sec--;
00050         ru1.tv.tv_usec += 1000000;
00051     }
00052     if (ru1.ru.ru_stime.tv_usec < ru0->ru.ru_stime.tv_usec)
00053     {
00054         ru1.ru.ru_stime.tv_sec--;
00055         ru1.ru.ru_stime.tv_usec += 1000000;
00056     }
00057     if (ru1.ru.ru_utime.tv_usec < ru0->ru.ru_utime.tv_usec)
00058     {
00059         ru1.ru.ru_utime.tv_sec--;
00060         ru1.ru.ru_utime.tv_usec += 1000000;
00061     }
00062 
00063     snprintf(result, sizeof(result),
00064              "CPU %d.%02ds/%d.%02du sec elapsed %d.%02d sec",
00065              (int) (ru1.ru.ru_stime.tv_sec - ru0->ru.ru_stime.tv_sec),
00066           (int) (ru1.ru.ru_stime.tv_usec - ru0->ru.ru_stime.tv_usec) / 10000,
00067              (int) (ru1.ru.ru_utime.tv_sec - ru0->ru.ru_utime.tv_sec),
00068           (int) (ru1.ru.ru_utime.tv_usec - ru0->ru.ru_utime.tv_usec) / 10000,
00069              (int) (ru1.tv.tv_sec - ru0->tv.tv_sec),
00070              (int) (ru1.tv.tv_usec - ru0->tv.tv_usec) / 10000);
00071 
00072     return result;
00073 }