Skip to content

Commit

Permalink
Use monotonic clock for performance.now() (#33983)
Browse files Browse the repository at this point in the history
Summary:
In #32695, the `Performance.now()` implementation changed to use unix epoch timestamps instead of a monotonic clock.

This is problematic, because it means that performance measurements get skewed if the device clock changes between two measurements.

With this change, the clock is now monotonic (and the implementation stays consistent between platforms).

More details and repro steps can be found in [this issue](#33977)
Closes #33977

## Changelog

[General] [Fixed] - Use monotonic clock for performance.now()

Pull Request resolved: #33983

Test Plan:
Run on iOS and Android:
```
const now = global.performance.now()
console.log(`${Platform.OS}: ${now}`)
```

Reviewed By: JoshuaGross, cipolleschi

Differential Revision: D37066999

Pulled By: dmitryrykun

fbshipit-source-id: 298547bf39faea1b025c17ff2d2e1a03f929865b
  • Loading branch information
Olivier Payen authored and fortmarek committed Jun 29, 2022
1 parent 74a08a3 commit dc334a2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
10 changes: 8 additions & 2 deletions React/CxxBridge/RCTJSIExecutorRuntimeInstaller.mm
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,14 @@
bindNativeLogger(runtime, iosLoggingBinder);

PerformanceNow iosPerformanceNowBinder = []() {
auto time = std::chrono::system_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::milliseconds>(time).count();
auto time = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(
time.time_since_epoch())
.count();

constexpr double NANOSECONDS_IN_MILLISECOND = 1000000.0;

return duration / NANOSECONDS_IN_MILLISECOND;
};
bindNativePerformanceNow(runtime, iosPerformanceNowBinder);

Expand Down
10 changes: 8 additions & 2 deletions ReactAndroid/src/main/jni/react/jni/NativeTime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,14 @@ namespace facebook {
namespace react {

double reactAndroidNativePerformanceNowHook() {
auto time = std::chrono::system_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::milliseconds>(time).count();
auto time = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(
time.time_since_epoch())
.count();

constexpr double NANOSECONDS_IN_MILLISECOND = 1000000.0;

return duration / NANOSECONDS_IN_MILLISECOND;
}

} // namespace react
Expand Down

0 comments on commit dc334a2

Please sign in to comment.