Try to avoid floating-point roundoff error in pg_sleep().
authorTom Lane <tgl@sss.pgh.pa.us>
Thu, 25 Sep 2025 21:02:15 +0000 (17:02 -0400)
committerTom Lane <tgl@sss.pgh.pa.us>
Thu, 25 Sep 2025 21:02:15 +0000 (17:02 -0400)
commit02c4bc88302a750a2aed20e6f17885bda872d228
treee1febbf58e2e18134beece3ec0382b9bd9a93e3b
parente849bd551c323a384f2b14d20a1b7bfaa6127ed7
Try to avoid floating-point roundoff error in pg_sleep().

I noticed the surprising behavior that pg_sleep(0.001) will sleep
for 2ms not the expected 1ms.  Apparently the float8 calculation of
time-to-sleep is managing to produce something a hair over 1, which
ceil() rounds up to 2, and then WaitLatch() faithfully waits 2ms.
It could be that this works as-expected for some ranges of current
timestamp but not others, which would account for not having seen
it before.  In any case, let's try to avoid it by removing the
float arithmetic in the delay calculation.  We're stuck with the
declared input type being float8, but we can convert that to integer
microseconds right away, and then work strictly with integral values.
There might still be roundoff surprises for certain input values,
but at least the behavior won't be time-varying.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Reviewed-by: Nathan Bossart <nathandbossart@gmail.com>
Discussion: https://postgr.es/m/3879137.1758825752@sss.pgh.pa.us
src/backend/utils/adt/misc.c