From aef72c0875b559eecb7e10abaf00e49186d7ae55 Mon Sep 17 00:00:00 2001 From: Marc Rousavy Date: Mon, 6 Dec 2021 11:11:59 +0100 Subject: [PATCH] feat: Add `performance.now()` to Worklets (#2679) ## Description Adds support for measuring performance/elapsed time in millisecond precision using Chrono with `performance.now()` in Worklets. ## Changes - Inject `_chronoNow` func in global runtime object ## Test code and steps to reproduce ```ts runOnUI(() => { 'worklet' const start = performance.now() for (let i = 0; i < 1000000; i++) {} const end = performance.now() console.log(`Loop took ${end - start} ms!`) })() ``` ## Checklist - [ ] Included code example that can be used to test this change - [ ] Updated TS types - [ ] Added TS types tests - [ ] Added unit / integration tests - [ ] Updated documentation - [ ] Ensured that CI passes ## Related Issues * https://github.com/facebook/react-native/pull/32695 --- Common/cpp/Tools/RuntimeDecorator.cpp | 17 +++++++++++++++++ src/reanimated2/core.ts | 3 +++ 2 files changed, 20 insertions(+) diff --git a/Common/cpp/Tools/RuntimeDecorator.cpp b/Common/cpp/Tools/RuntimeDecorator.cpp index 51613980e87..6dc1fdcbf46 100644 --- a/Common/cpp/Tools/RuntimeDecorator.cpp +++ b/Common/cpp/Tools/RuntimeDecorator.cpp @@ -1,4 +1,5 @@ #include "RuntimeDecorator.h" +#include #include #include #include "LayoutAnimationsProxy.h" @@ -83,6 +84,22 @@ void RuntimeDecorator::decorateRuntime( jsi::PropNameID::forAscii(rt, "_setGlobalConsole"), 1, setGlobalConsole)); + + rt.global().setProperty( + rt, + "_chronoNow", + jsi::Function::createFromHostFunction( + rt, + jsi::PropNameID::forAscii(rt, "_chronoNow"), + 0, + [](jsi::Runtime &rt, + const jsi::Value &thisValue, + const jsi::Value *args, + size_t count) -> jsi::Value { + double now = std::chrono::system_clock::now().time_since_epoch() / + std::chrono::milliseconds(1); + return jsi::Value(now); + })); } void RuntimeDecorator::decorateUIRuntime( diff --git a/src/reanimated2/core.ts b/src/reanimated2/core.ts index 3a8b9aa72cb..9bbd3888883 100644 --- a/src/reanimated2/core.ts +++ b/src/reanimated2/core.ts @@ -383,6 +383,9 @@ if (!NativeReanimatedModule.useOnlyV1) { info: runOnJS(capturableConsole.info), }; _setGlobalConsole(console); + global.performance = { + now: global._chronoNow, + }; })(); }