From 2211e60a47f8ff926e22c21433f9630bc4580bb6 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Fri, 21 Mar 2025 14:21:56 +0900
Subject: [PATCH 2/2] Trick to measure jumbling

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

diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 0554a4ae3c7b..e2365efe676b 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -873,6 +873,19 @@ pg_rewrite_query(Query *query)
 	return querytree_list;
 }
 
+#define NANOSEC_PER_SEC 1000000000
+
+#include <time.h>
+
+/* Returns difference between t1 and t2 in nanoseconds */
+static int64
+get_clock_diff(struct timespec *t1, struct timespec *t2)
+{
+	int64 nanosec = (t1->tv_sec - t2->tv_sec) * NANOSEC_PER_SEC;
+	nanosec += (t1->tv_nsec - t2->tv_nsec);
+
+	return nanosec;
+}
 
 /*
  * Generate a plan for a single already-rewritten query.
@@ -883,6 +896,8 @@ pg_plan_query(Query *querytree, const char *query_string, int cursorOptions,
 			  ParamListInfo boundParams)
 {
 	PlannedStmt *plan;
+	struct timespec start, end;
+	int64 jumbletime;
 
 	/* Utility commands have no plans. */
 	if (querytree->commandType == CMD_UTILITY)
@@ -896,6 +911,19 @@ pg_plan_query(Query *querytree, const char *query_string, int cursorOptions,
 	if (log_planner_stats)
 		ResetUsage();
 
+	if (IsQueryIdEnabled())
+	{
+		#define JUMBLE_LOOPS 100000
+		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
+		for (int i = 0; i < JUMBLE_LOOPS; i++)
+		{
+			JumbleQuery(querytree);
+		}
+		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);
+		jumbletime = get_clock_diff(&end, &start);
+		elog(NOTICE, "QueryJumble in %f ms", jumbletime / 1000000.0);
+	}
+
 	/* call the optimizer */
 	plan = planner(querytree, query_string, cursorOptions, boundParams);
 
-- 
2.49.0