Skip to content

Commit c149180

Browse files
committed
fix: Use monotonic clock to compute durations
A monotonic clock is monotonically increasing and not subject to system clock adjustments or system clock skew. The difference between any two chronologically recorded time values returned from the Performance.now() method MUST never be negative if the two time values have the same time origin. The same guarantee above does not exist for the difference between two calls to `new Date().getTime()` as used by `timestampWithMs()`. Resources: https://stackoverflow.com/questions/7272395/monotonically-increasing-time-in-javascript https://caniuse.com/#search=performance.now https://www.w3.org/TR/hr-time/#sec-monotonic-clock
1 parent 47771a1 commit c149180

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

packages/apm/src/span.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,17 @@ export class Span implements SpanInterface, SpanContext {
8181
*/
8282
public readonly startTimestamp: number = timestampWithMs();
8383

84+
/**
85+
* Internal start time tracked with a monotonic clock.
86+
*
87+
* Works with mostly any browser version released since 2012.
88+
* https://caniuse.com/#search=performance.now
89+
*
90+
* Works with Node.js v8.5.0 or higher.
91+
* https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_now
92+
*/
93+
private readonly _startTimestampMonotonic: number = performance.now();
94+
8495
/**
8596
* Finish timestamp of the span.
8697
*/
@@ -261,7 +272,9 @@ export class Span implements SpanInterface, SpanContext {
261272
return undefined;
262273
}
263274

264-
this.timestamp = timestampWithMs();
275+
// TODO: Fallback to timestampWithMs() when performance.now is unavailable.
276+
const durationSeconds = (performance.now() - this._startTimestampMonotonic) / 1000;
277+
this.timestamp = this.startTimestamp + durationSeconds;
265278

266279
if (this.spanRecorder === undefined) {
267280
return undefined;

0 commit comments

Comments
 (0)