instrumentation: Standardize ticks to nanosecond conversion method
Andres Freund <andres@anarazel.de>
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 <lukas@fittl.com> Author: David Geier <geidav.pg@gmail.com> Author: Andres Freund <andres@anarazel.de> Reviewed-by: Andres Freund <andres@anarazel.de> Reviewed-by: David Geier <geidav.pg@gmail.com> Reviewed-by: Lukas Fittl <lukas@fittl.com> Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com> Discussion: https://www.postgresql.org/message-id/flat/20200612232810.f46nbqkdhbutzqdg%40alap3.anarazel.de
Files
| Path | Change | +/− |
|---|---|---|
| src/backend/postmaster/postmaster.c | modified | +3 −0 |
| src/bin/pgbench/pgbench.c | modified | +3 −0 |
| src/bin/pg_test_timing/pg_test_timing.c | modified | +3 −0 |
| src/bin/psql/startup.c | modified | +4 −0 |
| src/common/instr_time.c | added | +106 −0 |
| src/common/Makefile | modified | +1 −0 |
| src/common/meson.build | modified | +1 −0 |
| src/include/portability/instr_time.h | modified | +118 −31 |
| src/test/regress/expected/misc_functions.out | modified | +11 −0 |
| src/test/regress/pg_regress.c | modified | +2 −0 |
| src/test/regress/regress.c | modified | +36 −0 |
| src/test/regress/sql/misc_functions.sql | modified | +7 −0 |
Discussion
- Reduce timing overhead of EXPLAIN ANALYZE using rdtsc? 172 messages · 2020-06-12 → 2026-05-16