-
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathbench.ts
More file actions
383 lines (338 loc) · 9.82 KB
/
Copy pathbench.ts
File metadata and controls
383 lines (338 loc) · 9.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import type {
AddEventListenerOptionsArgument,
BenchEvents,
BenchLike,
BenchOptions,
EventListener,
EventListenerObject,
Fn,
FnOptions,
JSRuntime,
RemoveEventListenerOptionsArgument,
TaskResult,
TimestampProvider,
} from './types'
import {
defaultMinimumIterations as defaultIterations,
defaultMinimumWarmupTime,
defaultMinimumTime as defaultTime,
defaultMinimumWarmupIterations as defaultWarmupIterations,
emptyFunction,
} from './constants'
import { BenchEvent } from './event'
import { Task } from './task'
import {
assert,
calibrateTimerOverhead,
defaultConvertTaskResultForConsoleTable,
getTimestampProvider,
runtime,
runtimeVersion,
} from './utils'
/**
* The Bench class keeps track of the benchmark tasks and controls them.
*/
export class Bench extends EventTarget implements BenchLike {
declare addEventListener: <K extends BenchEvents>(
type: K,
listener: EventListener<K> | EventListenerObject<K> | null,
options?: AddEventListenerOptionsArgument
) => void
/**
* Executes tasks concurrently based on the specified concurrency mode.
*
* - When `mode` is set to `null` (default), concurrency is disabled.
* - When `mode` is set to 'task', each task's iterations (calls of a task function) run concurrently.
* - When `mode` is set to 'bench', different tasks within the bench run concurrently.
*/
readonly concurrency: 'bench' | 'task' | null
/**
* The amount of executions per task.
*/
readonly iterations: number
/**
* The benchmark name.
*/
readonly name: string | undefined
/**
* A function to get a timestamp.
*/
readonly now: () => number
/**
* Removes a previously registered event listener.
*/
declare removeEventListener: <K extends BenchEvents>(
type: K,
listener: EventListener<K> | EventListenerObject<K> | null,
options?: RemoveEventListenerOptionsArgument
) => void
readonly retainSamples: boolean
/**
* The JavaScript runtime environment.
*/
readonly runtime: JSRuntime
/**
* The JavaScript runtime version.
*/
readonly runtimeVersion: string
/**
* A setup function that runs before each task execution.
*/
readonly setup: (task: Task, mode: 'run' | 'warmup') => Promise<void> | void
/**
* An AbortSignal to cancel the benchmark.
*/
readonly signal?: AbortSignal
/**
* Whether to subtract an estimated timestamp provider call overhead from
* each raw latency sample.
*
* Incompatible with `concurrency: 'task'`; the constraint is enforced
* at construction and at the start of {@link Bench.run}.
* @default false
*/
readonly subtractTimerOverhead: boolean
/**
* A teardown function that runs after each task execution.
*/
readonly teardown: (
task: Task,
mode: 'run' | 'warmup'
) => Promise<void> | void
/**
* The maximum number of concurrent tasks to run
* @default Number.POSITIVE_INFINITY
*/
readonly threshold: number
/**
* Whether to throw an error if a task function throws
* @default false
*/
readonly throws: boolean
/**
* The amount of time to run each task.
*/
readonly time: number
/**
* The estimated cost of one timestamp provider call in milliseconds.
*
* `undefined` when {@link subtractTimerOverhead} is `false`.
* Otherwise calibrated once at construction time via
* {@link calibrateTimerOverhead}.
*/
readonly timerOverhead: number | undefined
/**
* A timestamp provider and its related functions.
*/
readonly timestampProvider: TimestampProvider
/**
* Whether to warmup the tasks before running them
*/
readonly warmup: boolean
/**
* The amount of warmup iterations per task.
*/
readonly warmupIterations: number
/**
* The amount of time to warmup each task.
*/
readonly warmupTime: number
/**
* The tasks results as an array.
* @returns the tasks results
*/
get results (): Readonly<TaskResult>[] {
return this.tasks.map(task => task.result)
}
/**
* The tasks as an array.
* @returns An array containing all benchmark tasks
*/
get tasks (): Task[] {
return [...this.#tasks.values()]
}
/**
* The task map
*/
readonly #tasks: Map<string, Task> = new Map<string, Task>()
constructor (options: BenchOptions = {}) {
super()
const { name, ...restOptions } = options
this.name = name
this.runtime = runtime
this.runtimeVersion = runtimeVersion
this.concurrency = restOptions.concurrency ?? null
this.threshold = restOptions.threshold ?? Number.POSITIVE_INFINITY
this.time = restOptions.time ?? defaultTime
this.iterations = restOptions.iterations ?? defaultIterations
assert(
!(
restOptions.now !== undefined &&
restOptions.timestampProvider !== undefined
),
'Cannot set both `now` and `timestampProvider` options'
)
this.timestampProvider = getTimestampProvider(
restOptions.now ?? restOptions.timestampProvider
)
this.now = () => this.timestampProvider.toMs(this.timestampProvider.fn())
this.warmup = restOptions.warmup ?? true
this.warmupIterations =
restOptions.warmupIterations ?? defaultWarmupIterations
this.warmupTime = restOptions.warmupTime ?? defaultMinimumWarmupTime
this.setup = restOptions.setup ?? emptyFunction
this.teardown = restOptions.teardown ?? emptyFunction
this.throws = restOptions.throws ?? false
this.signal = restOptions.signal
this.retainSamples = restOptions.retainSamples === true
this.subtractTimerOverhead = restOptions.subtractTimerOverhead === true
assert(
!(this.subtractTimerOverhead && this.concurrency === 'task'),
'`subtractTimerOverhead` cannot be used with `concurrency: "task"` — set `concurrency` to `null` or `"bench"`, or disable `subtractTimerOverhead`'
)
this.timerOverhead = this.subtractTimerOverhead
? calibrateTimerOverhead(this.timestampProvider)
: undefined
if (this.signal) {
this.signal.addEventListener(
'abort',
() => {
this.dispatchEvent(new BenchEvent('abort'))
},
{ once: true }
)
}
}
/**
* Adds a benchmark task to the task map.
* @param name - the task name
* @param fn - the task function
* @param fnOpts - the task function options
* @returns the Bench instance
* @throws {Error} when a task with the same name already exists
*/
add (name: string, fn: Fn, fnOpts: FnOptions = {}): this {
if (!this.#tasks.has(name)) {
const task = new Task(this, name, fn, fnOpts)
this.#tasks.set(name, task)
this.dispatchEvent(new BenchEvent('add', task))
} else {
throw new Error(`Task "${name}" already exists`)
}
return this
}
/**
* Gets a task based on the task name.
* @param name - the task name
* @returns the Task instance or undefined if not found
*/
getTask (name: string): Task | undefined {
return this.#tasks.get(name)
}
/**
* Removes a benchmark task from the task map.
* @param name - the task name
* @returns the Bench instance
*/
remove (name: string): this {
const task = this.getTask(name)
if (task) {
this.#tasks.delete(name)
this.dispatchEvent(new BenchEvent('remove', task))
}
return this
}
/**
* Resets all tasks and removes their results.
*/
reset (): void {
for (const task of this.#tasks.values()) {
task.reset()
}
this.dispatchEvent(new BenchEvent('reset'))
}
/**
* Runs the added benchmark tasks.
* @returns the tasks array
*/
async run (): Promise<Task[]> {
assert(
!(this.subtractTimerOverhead && this.concurrency === 'task'),
'`subtractTimerOverhead` cannot be used with `concurrency: "task"` — set `concurrency` to `null` or `"bench"`, or disable `subtractTimerOverhead`'
)
if (this.warmup) {
await this.#warmupTasks()
}
this.dispatchEvent(new BenchEvent('start'))
let values: Task[] = []
if (this.concurrency === 'bench') {
const taskPromises = []
for (const task of this.#tasks.values()) {
taskPromises.push(task.run())
}
values = await Promise.all(taskPromises)
} else {
for (const task of this.#tasks.values()) {
values.push(await task.run())
}
}
this.dispatchEvent(new BenchEvent('complete'))
return values
}
/**
* Runs the added benchmark tasks synchronously.
* @returns the tasks array
*/
runSync (): Task[] {
assert(
this.concurrency === null,
'Cannot use `concurrency` option when using `runSync`'
)
if (this.warmup) {
this.#warmupTasksSync()
}
const values: Task[] = []
this.dispatchEvent(new BenchEvent('start'))
for (const task of this.#tasks.values()) {
values.push(task.runSync())
}
this.dispatchEvent(new BenchEvent('complete'))
return values
}
/**
* Returns the tasks results as a table.
* @param convert - an optional callback to convert the task result to a table record
* @returns the tasks results as an array of table records
*/
table (
convert = defaultConvertTaskResultForConsoleTable
): (null | Record<string, number | string | undefined>)[] {
return this.tasks.map(convert)
}
/**
* Warms up the benchmark tasks.
*/
async #warmupTasks (): Promise<void> {
this.dispatchEvent(new BenchEvent('warmup'))
if (this.concurrency === 'bench') {
const taskPromises = []
for (const task of this.#tasks.values()) {
taskPromises.push(task.warmup())
}
await Promise.all(taskPromises)
} else {
for (const task of this.#tasks.values()) {
await task.warmup()
}
}
}
/**
* Warms up the benchmark tasks synchronously.
*/
#warmupTasksSync (): void {
this.dispatchEvent(new BenchEvent('warmup'))
for (const task of this.#tasks.values()) {
task.warmupSync()
}
}
}