0
# Timing Utilities
1
2
High-resolution timing utilities with nanosecond precision and monotonic clock support for accurate span timing and performance measurement.
3
4
## Capabilities
5
6
### Anchored Clock
7
8
A utility for returning wall times anchored to a given point in time, ensuring accurate span timings that don't drift from system clock corrections.
9
10
```typescript { .api }
11
/**
12
* Clock interface for time sources
13
*/
14
interface Clock {
15
/**
16
* Return the current time in milliseconds from some epoch such as Unix epoch or process start
17
*/
18
now(): number;
19
}
20
21
/**
22
* A utility for returning wall times anchored to a given point in time.
23
* Wall time measurements are computed by adding a monotonic clock time
24
* to the anchor point, preventing span timing issues from system clock changes.
25
*/
26
class AnchoredClock implements Clock {
27
/**
28
* Create a new AnchoredClock anchored to the current time returned by systemClock
29
* @param systemClock - Clock that returns milliseconds since January 1 1970 (like Date)
30
* @param monotonicClock - Clock that counts milliseconds monotonically (like performance)
31
*/
32
constructor(systemClock: Clock, monotonicClock: Clock);
33
34
/**
35
* Returns the current time by adding the number of milliseconds since the
36
* AnchoredClock was created to the creation epoch time
37
* @returns Current anchored time in milliseconds
38
*/
39
now(): number;
40
}
41
```
42
43
**Usage Examples:**
44
45
```typescript
46
import { AnchoredClock } from "@opentelemetry/core";
47
48
// Create clocks for system time and performance measurement
49
const systemClock = { now: () => Date.now() };
50
const performanceClock = { now: () => performance.now() };
51
52
// Create anchored clock for consistent timing
53
const anchoredClock = new AnchoredClock(systemClock, performanceClock);
54
55
// Use for span timing
56
const startTime = anchoredClock.now();
57
// ... some operation ...
58
const endTime = anchoredClock.now();
59
const duration = endTime - startTime;
60
61
// Times remain consistent even if system clock is adjusted
62
console.log(`Operation took ${duration}ms`);
63
```
64
65
### High-Resolution Time Functions
66
67
Functions for working with high-resolution time ([seconds, nanoseconds] tuples) with nanosecond precision.
68
69
```typescript { .api }
70
/**
71
* Get current HrTime based on performance timing
72
* @param performanceNow - Optional performance.now() value to use instead of current time
73
* @returns HrTime array [seconds, nanoseconds]
74
*/
75
function hrTime(performanceNow?: number): HrTime;
76
77
/**
78
* Convert milliseconds from epoch to HrTime
79
* @param epochMillis - Milliseconds since Unix epoch
80
* @returns HrTime array [seconds, nanoseconds]
81
*/
82
function millisToHrTime(epochMillis: number): HrTime;
83
84
/**
85
* Convert various time inputs to HrTime format
86
* @param time - Time input (HrTime, number, or Date)
87
* @returns HrTime array [seconds, nanoseconds]
88
*/
89
function timeInputToHrTime(time: TimeInput): HrTime;
90
91
/**
92
* Calculate duration between two HrTime values
93
* @param startTime - Start time as HrTime
94
* @param endTime - End time as HrTime
95
* @returns Duration as HrTime [seconds, nanoseconds]
96
*/
97
function hrTimeDuration(startTime: HrTime, endTime: HrTime): HrTime;
98
99
/**
100
* Add two HrTime values together
101
* @param time1 - First HrTime value
102
* @param time2 - Second HrTime value
103
* @returns Sum as HrTime [seconds, nanoseconds]
104
*/
105
function addHrTimes(time1: HrTime, time2: HrTime): HrTime;
106
```
107
108
**Usage Examples:**
109
110
```typescript
111
import {
112
hrTime,
113
hrTimeDuration,
114
millisToHrTime,
115
timeInputToHrTime,
116
addHrTimes
117
} from "@opentelemetry/core";
118
119
// Get current high-resolution time
120
const now = hrTime();
121
console.log(now); // [1609459200, 123456789] (seconds, nanoseconds)
122
123
// Convert from milliseconds
124
const epochTime = millisToHrTime(Date.now());
125
126
// Convert various time formats
127
const hrFromDate = timeInputToHrTime(new Date());
128
const hrFromNumber = timeInputToHrTime(performance.now());
129
const hrFromHrTime = timeInputToHrTime([1609459200, 123456789]);
130
131
// Calculate duration between operations
132
const startTime = hrTime();
133
// ... some async operation ...
134
const endTime = hrTime();
135
const duration = hrTimeDuration(startTime, endTime);
136
137
console.log(`Operation took ${duration[0]} seconds and ${duration[1]} nanoseconds`);
138
139
// Add times together
140
const totalTime = addHrTimes(duration, [0, 500000000]); // Add 500ms
141
```
142
143
### Time Conversion Functions
144
145
Functions to convert HrTime to various other time formats.
146
147
```typescript { .api }
148
/**
149
* Convert HrTime to nanoseconds
150
* @param time - HrTime array [seconds, nanoseconds]
151
* @returns Total nanoseconds as number
152
*/
153
function hrTimeToNanoseconds(time: HrTime): number;
154
155
/**
156
* Convert HrTime to milliseconds
157
* @param time - HrTime array [seconds, nanoseconds]
158
* @returns Total milliseconds as number
159
*/
160
function hrTimeToMilliseconds(time: HrTime): number;
161
162
/**
163
* Convert HrTime to microseconds
164
* @param time - HrTime array [seconds, nanoseconds]
165
* @returns Total microseconds as number
166
*/
167
function hrTimeToMicroseconds(time: HrTime): number;
168
169
/**
170
* Convert HrTime to ISO timestamp string
171
* @param time - HrTime array [seconds, nanoseconds]
172
* @returns ISO timestamp string with nanosecond precision
173
*/
174
function hrTimeToTimeStamp(time: HrTime): string;
175
176
/**
177
* Get performance timeOrigin value (with fallback for older browsers)
178
* @returns Time origin in milliseconds
179
*/
180
function getTimeOrigin(): number;
181
```
182
183
**Usage Examples:**
184
185
```typescript
186
import {
187
hrTimeToNanoseconds,
188
hrTimeToMilliseconds,
189
hrTimeToMicroseconds,
190
hrTimeToTimeStamp,
191
hrTime
192
} from "@opentelemetry/core";
193
194
const time = hrTime();
195
196
// Convert to different units
197
const nanos = hrTimeToNanoseconds(time);
198
const millis = hrTimeToMilliseconds(time);
199
const micros = hrTimeToMicroseconds(time);
200
201
console.log(`${nanos} nanoseconds`);
202
console.log(`${millis} milliseconds`);
203
console.log(`${micros} microseconds`);
204
205
// Convert to ISO timestamp with nanosecond precision
206
const timestamp = hrTimeToTimeStamp(time);
207
console.log(timestamp); // "2021-01-01T00:00:00.123456789Z"
208
209
// Use for span attributes
210
const spanAttributes = {
211
'timing.start': hrTimeToNanoseconds(startTime),
212
'timing.end': hrTimeToNanoseconds(endTime),
213
'timing.timestamp': hrTimeToTimeStamp(time)
214
};
215
```
216
217
### Time Validation Functions
218
219
Type guard functions to validate time input values.
220
221
```typescript { .api }
222
/**
223
* Check if value is HrTime format
224
* @param value - Value to check
225
* @returns True if value is HrTime [seconds, nanoseconds]
226
*/
227
function isTimeInputHrTime(value: unknown): value is HrTime;
228
229
/**
230
* Check if value is a valid TimeInput type
231
* @param value - Value to check
232
* @returns True if value is HrTime, number, or Date
233
*/
234
function isTimeInput(value: unknown): value is HrTime | number | Date;
235
```
236
237
**Usage Examples:**
238
239
```typescript
240
import { isTimeInputHrTime, isTimeInput, timeInputToHrTime } from "@opentelemetry/core";
241
242
function processTimeValue(value: unknown) {
243
if (isTimeInput(value)) {
244
const hrTime = timeInputToHrTime(value);
245
console.log("Valid time input converted to HrTime:", hrTime);
246
247
if (isTimeInputHrTime(value)) {
248
console.log("Input was already in HrTime format");
249
}
250
} else {
251
console.error("Invalid time input");
252
}
253
}
254
255
// Test with different input types
256
processTimeValue([1609459200, 123456789]); // HrTime
257
processTimeValue(Date.now()); // number
258
processTimeValue(new Date()); // Date
259
processTimeValue("invalid"); // Will log error
260
```