instrumentation: Standardize ticks to nanosecond conversion method

The timing infrastructure (INSTR_* macros) measures time elapsed using
clock_gettime() on POSIX systems, which returns the time as nanoseconds,
and QueryPerformanceCounter() on Windows, which is a specialized timing
clock source that returns a tick counter that needs to be converted to
nanoseconds using the result of QueryPerformanceFrequency().

This conversion currently happens ad-hoc on Windows, e.g. when calling
INSTR_TIME_GET_NANOSEC, which calls QueryPerformanceFrequency() on every
invocation, despite the frequency being stable after program start,
incurring unnecessary overhead. It also causes a fractured implementation
where macros are defined differently between platforms.

To ease code readability, and prepare for a future change that intends
to use a ticks-to-nanosecond conversion on x86-64 for TSC use, introduce
new pg_ticks_to_ns() / pg_ns_to_ticks() functions that get called from
INSTR_* macros on all platforms.

These functions rely on a separately initialized ticks_per_ns_scaled
value, that represents the conversion ratio. This value is initialized
from QueryPerformanceFrequency() on Windows, and set to zero on x86-64
POSIX systems, which results in the ticks being treated as nanoseconds.
Other architectures always directly return the original ticks.

To support this, pg_initialize_timing() is introduced, and is now
mandatory for both the backend and any frontend programs to call before
utilizing INSTR_* macros.

In passing, fix variable names in comment documenting INSTR_TIME_ADD_NANOSEC().

Author: Lukas Fittl <[email protected]>
Author: David Geier <[email protected]>
Author: Andres Freund <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Reviewed-by: David Geier <[email protected]>
Reviewed-by: Lukas Fittl <[email protected]>
Reviewed-by: Zsolt Parragi <[email protected]>
Discussion: 
https://www.postgresql.org/message-id/flat/20200612232810.f46nbqkdhbutzqdg%40alap3.anarazel.de

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/0022622c93d9e6419cb47110c58af87a74994ea6

Modified Files
--------------
src/backend/postmaster/postmaster.c          |   3 +
src/bin/pg_test_timing/pg_test_timing.c      |   3 +
src/bin/pgbench/pgbench.c                    |   3 +
src/bin/psql/startup.c                       |   4 +
src/common/Makefile                          |   1 +
src/common/instr_time.c                      | 106 +++++++++++++++++++
src/common/meson.build                       |   1 +
src/include/portability/instr_time.h         | 149 +++++++++++++++++++++------
src/test/regress/expected/misc_functions.out |  11 ++
src/test/regress/pg_regress.c                |   2 +
src/test/regress/regress.c                   |  36 +++++++
src/test/regress/sql/misc_functions.sql      |   7 ++
12 files changed, 295 insertions(+), 31 deletions(-)

Reply via email to