From b54ce31f2e0f1965e67dda171510aa3b3f5efd0b Mon Sep 17 00:00:00 2001
From: Jianghua Yang <yjhjstz@gmail.com>
Date: Thu, 27 Mar 2025 23:59:26 +0800
Subject: [PATCH] Add optional support for CLOCK_MONOTONIC_COARSE only for
 explain analyze.

---
 src/backend/executor/instrument.c    |  2 +-
 src/include/portability/instr_time.h | 23 ++++++++++++++++++++++-
 2 files changed, 23 insertions(+), 2 deletions(-)

diff --git a/src/backend/executor/instrument.c b/src/backend/executor/instrument.c
index 268ae8a945f..23de5b1b5c5 100644
--- a/src/backend/executor/instrument.c
+++ b/src/backend/executor/instrument.c
@@ -95,7 +95,7 @@ InstrStopNode(Instrumentation *instr, double nTuples)
 		if (INSTR_TIME_IS_ZERO(instr->starttime))
 			elog(ERROR, "InstrStopNode called without start");
 
-		INSTR_TIME_SET_CURRENT(endtime);
+		INSTR_TIME_SET_CURRENT_COARSE(endtime);
 		INSTR_TIME_ACCUM_DIFF(instr->counter, endtime, instr->starttime);
 
 		INSTR_TIME_SET_ZERO(instr->starttime);
diff --git a/src/include/portability/instr_time.h b/src/include/portability/instr_time.h
index a9fc71b186a..ca2679276fb 100644
--- a/src/include/portability/instr_time.h
+++ b/src/include/portability/instr_time.h
@@ -137,6 +137,25 @@ pg_clock_gettime_ns(void)
 #define INSTR_TIME_GET_NANOSEC(t) \
 	((int64) (t).ticks)
 
+#ifdef CLOCK_MONOTONIC_COARSE
+/* helper for INSTR_TIME_SET_CURRENT_COARSE */
+static inline instr_time
+pg_clock_gettime_ns_coarse(void)
+{
+	instr_time	now;
+	struct timespec tmp;
+
+	clock_gettime(CLOCK_MONOTONIC_COARSE, &tmp);
+	now.ticks = tmp.tv_sec * NS_PER_S + tmp.tv_nsec;
+
+	return now;
+}
+
+#define INSTR_TIME_SET_CURRENT_COARSE(t)	((t) = pg_clock_gettime_ns_coarse())
+#else
+#define INSTR_TIME_SET_CURRENT_COARSE(t)	INSTR_TIME_SET_CURRENT(t)
+#endif
+
 
 #else							/* WIN32 */
 
@@ -171,6 +190,8 @@ GetTimerFrequency(void)
 #define INSTR_TIME_GET_NANOSEC(t) \
 	((int64) ((t).ticks * ((double) NS_PER_S / GetTimerFrequency())))
 
+#define INSTR_TIME_SET_CURRENT_COARSE(t)	INSTR_TIME_SET_CURRENT(t)
+
 #endif							/* WIN32 */
 
 
@@ -184,7 +205,7 @@ GetTimerFrequency(void)
 #define INSTR_TIME_SET_ZERO(t)	((t).ticks = 0)
 
 #define INSTR_TIME_SET_CURRENT_LAZY(t) \
-	(INSTR_TIME_IS_ZERO(t) ? INSTR_TIME_SET_CURRENT(t), true : false)
+	(INSTR_TIME_IS_ZERO(t) ? INSTR_TIME_SET_CURRENT_COARSE(t), true : false)
 
 
 #define INSTR_TIME_ADD(x,y) \
-- 
2.25.1

