From 51a7b458db74c1c285688ab9991fe590c9c97357 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Wed, 16 Jun 2021 14:49:22 +0900
Subject: [PATCH v10 2/2] Add tweak to test CPU usage within a session, for
 wal_compression

---
 src/backend/tcop/postgres.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 8cea10c901..2d7affe115 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -178,6 +178,10 @@ static bool RecoveryConflictPending = false;
 static bool RecoveryConflictRetryable = true;
 static ProcSignalReason RecoveryConflictReason;
 
+/* Amount of user and system time used, tracked at start */
+static struct timeval user_time;
+static struct timeval system_time;
+
 /* reused buffer to pass to SendRowDescriptionMessage() */
 static MemoryContext row_description_context = NULL;
 static StringInfoData row_description_buf;
@@ -3937,6 +3941,12 @@ PostgresMain(int argc, char *argv[],
 	volatile bool send_ready_for_query = true;
 	bool		idle_in_transaction_timeout_enabled = false;
 	bool		idle_session_timeout_enabled = false;
+	struct rusage r;
+
+	/* Get start usage for reference point */
+	getrusage(RUSAGE_SELF, &r);
+	memcpy((char *) &user_time, (char *) &r.ru_utime, sizeof(user_time));
+	memcpy((char *) &system_time, (char *) &r.ru_stime, sizeof(system_time));
 
 	/* Initialize startup process environment if necessary. */
 	if (!IsUnderPostmaster)
@@ -4683,6 +4693,14 @@ PostgresMain(int argc, char *argv[],
 
 			case 'X':
 
+				/* Get stop status of process and log comparison with start */
+				getrusage(RUSAGE_SELF, &r);
+				elog(LOG,"user diff: %ld.%06ld, system diff: %ld.%06ld",
+					 (long) (r.ru_utime.tv_sec - user_time.tv_sec),
+					 (long) (r.ru_utime.tv_usec - user_time.tv_usec),
+					 (long) (r.ru_stime.tv_sec - system_time.tv_sec),
+					 (long) (r.ru_stime.tv_usec - system_time.tv_usec));
+
 				/*
 				 * Reset whereToSendOutput to prevent ereport from attempting
 				 * to send any more messages to client.
-- 
2.32.0

