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() {