TStopwatch Cross-Platform Timer Resolution Consistency
0 reputation · 06 Jul 2022, 15:09 UTC
0 reputation · 06 Jul 2022, 15:09 UTC
The TStopwatch record in Delphi measures elapsed time using platform-specific monotonic clocks.
Windows typically uses QueryPerformanceCounter, while other targets employ different clock sources.
Is the reported TStopwatch.Frequency reliably comparable across Windows, macOS, and mobile targets without explicit platform-specific checks?
ElapsedMilliseconds across all supported targets?TStopwatch inherently provide thread-safe timing measurement for concurrent operations?37275 reputation · 07 Jul 2022, 00:54 UTC
The TStopwatch record in Delphi wraps platform-native monotonic clocks to measure elapsed time. Its Frequency field reports the tick rate of the underlying counter, and ElapsedMilliseconds converts accumulated ticks into whole-millisecond units.
Direct answer: No, the reported TStopwatch.Frequency is not reliably comparable across Windows, macOS, and mobile targets without explicit platform-specific checks. Each operating system exposes a different monotonic clock source - Windows typically uses QueryPerformanceCounter, Apple platforms use mach_absolute_time or clock_gettime, and Android/iOS map to CLOCK_MONOTONIC or equivalent hardware counters. The numeric Frequency value differs by OS and hardware, so assuming equal Frequency implies equal resolution is unsafe.
Delphi documentation states that ElapsedMilliseconds truncates to whole milliseconds. Sub-millisecond granularity depends on the resolution of the platform clock source and may vary with hardware generation, power-management states, or OS version. No fixed precision guarantee is documented for all supported targets.
TStopwatch is a record value type. A single instance is not inherently thread-safe for concurrent Start, Stop, or Elapsed access from multiple threads without external synchronization. Simultaneous writes can produce inconsistent or negative elapsed values.
If you must time operations from multiple threads, create a separate TStopwatch instance per thread or protect access with a critical section.
If you can share the specific RAD Studio version and target platform, I can refine the recommendation to platform-specific defaults or known caveats.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.