From dc898cc5d8d62ebc3505e5248a2e9b017db216ce Mon Sep 17 00:00:00 2001 From: Nick Lefever Date: Wed, 9 Apr 2025 04:53:23 -0700 Subject: [PATCH] Add high resolution CPU time support on macOS (#50553) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/50553 Adding nanosecond resolution for macOS to the NativeCPUTime native module. This allows for running Fantom benchmarks on macOS with high resolution CPUTime counters. This change adds the internal `getCPUTimeConversionFactor` function which is needed to convert the output from `mach_absolute_time` to a double representing time in nanoseconds. The native module calls `getCPUTTimeConversionFactor` once in the constructor and stores the result for future calls. The conversion factor defaults to 1.0 for all other platforms. Changelog: [internal] Reviewed By: rubennorte Differential Revision: D72631963 fbshipit-source-id: 33fa1bfc576e634187091bfa668106e31cc62214 --- .../react/nativemodule/cputime/CPUTime.h | 32 +++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/packages/react-native/ReactCommon/react/nativemodule/cputime/CPUTime.h b/packages/react-native/ReactCommon/react/nativemodule/cputime/CPUTime.h index fe260ff03f2..fa78ed5e616 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/cputime/CPUTime.h +++ b/packages/react-native/ReactCommon/react/nativemodule/cputime/CPUTime.h @@ -7,8 +7,10 @@ #pragma once -#ifdef USE_POSIX_TIME +#if defined USE_POSIX_TIME #include +#elif defined __MACH__ +#include #else #include #endif @@ -21,9 +23,23 @@ const double NANOSECONDS_IN_A_SECOND = 1000000000; #endif +#ifdef __MACH__ + +namespace { +inline double getConversionFactor() { + double conversionFactor; + mach_timebase_info_data_t info; + mach_timebase_info(&info); + conversionFactor = static_cast(info.numer) / info.denom; + return conversionFactor; +} +} // namespace + +#endif + namespace facebook::react { -#ifdef USE_POSIX_TIME +#if defined USE_POSIX_TIME inline double getCPUTimeNanos() { struct timespec time {}; @@ -36,6 +52,18 @@ inline bool hasAccurateCPUTimeNanosForBenchmarks() { return true; } +#elif defined __MACH__ + +inline double getCPUTimeNanos() { + static auto conversionFactor = getConversionFactor(); + uint64_t time = mach_absolute_time(); + return static_cast(time) * conversionFactor; +} + +inline bool hasAccurateCPUTimeNanosForBenchmarks() { + return true; +} + #else inline double getCPUTimeNanos() {