From 951820a8e312584f283ef4b5bde006c7f41e0d9d Mon Sep 17 00:00:00 2001
From: Laurenz Albe <laurenz.albe@cybertec.at>
Date: Wed, 18 Aug 2021 04:52:57 +0200
Subject: [PATCH] Improve performance and accuracy of session statistics

Rather than calling GetCurrentTimestamp() in pgstat_send_connstats(),
which causes an additional system call, reuse the value just
calculated in pgstat_report_stat().

Since the "now" value in pgstat_report_stat() will become the next
"last_report" value, this will also improve the accuracy of the
statistics, since the timestamp difference calculated in
pgstat_send_connstats() will become the correct one.

This patch does not address the issue that yet another UDP packet
is sent to the statistics collector for session statistics.

Discussion: https://postgr.es/m/20210801205501.nyxzxoelqoo4x2qc%40alap3.anarazel.de
---
 src/backend/postmaster/pgstat.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/backend/postmaster/pgstat.c b/src/backend/postmaster/pgstat.c
index ce8888cc30..77d734a0ba 100644
--- a/src/backend/postmaster/pgstat.c
+++ b/src/backend/postmaster/pgstat.c
@@ -324,7 +324,7 @@ static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
 static void pgstat_send_funcstats(void);
 static void pgstat_send_slru(void);
 static HTAB *pgstat_collect_oids(Oid catalogid, AttrNumber anum_oid);
-static void pgstat_send_connstats(bool disconnect, TimestampTz last_report);
+static void pgstat_send_connstats(bool disconnect, TimestampTz last_report, TimestampTz now);
 
 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
 
@@ -879,7 +879,7 @@ pgstat_report_stat(bool disconnect)
 
 	/* for backends, send connection statistics */
 	if (MyBackendType == B_BACKEND)
-		pgstat_send_connstats(disconnect, last_report);
+		pgstat_send_connstats(disconnect, last_report, now);
 
 	last_report = now;
 
@@ -1375,7 +1375,7 @@ pgstat_drop_relation(Oid relid)
  * ----------
  */
 static void
-pgstat_send_connstats(bool disconnect, TimestampTz last_report)
+pgstat_send_connstats(bool disconnect, TimestampTz last_report, TimestampTz now)
 {
 	PgStat_MsgConn msg;
 	long		secs;
@@ -1389,7 +1389,7 @@ pgstat_send_connstats(bool disconnect, TimestampTz last_report)
 
 	/* session time since the last report */
 	TimestampDifference(((last_report == 0) ? MyStartTimestamp : last_report),
-						GetCurrentTimestamp(),
+						now,
 						&secs, &usecs);
 	msg.m_session_time = secs * 1000000 + usecs;
 
-- 
2.26.3

