a stopwatch class that provides convince methods for timing. this module exports a global defaultStopwatch available to all importing scripts, which is beneficial if you want to use a single stop watch across many modules, otherwise, if you want a dedicated stopwatch, you can create a new instance of this class.

this stopwatch operates on the principals of a stack data-structure: that is, you can push, pop, and seek the time. the Delta methods provide the elapsed time since the last push.

import { assertGreater, assertLess, assertThrows } from "jsr:@std/assert"

const stop_watch = new Stopwatch("perf")
stop_watch.push()
const
resolved_value: "hello" = await (new Promise((resolve) => {
setTimeout(() => { resolve("hello") }, 300)
})),
delta_time = stop_watch.popDelta(),
log = `execution time: ${delta_time} ms`
assertGreater(delta_time, 290) // completing the promise should take more than `290` milliseconds
assertLess(delta_time, 400) // completing the promise should take less than `400` milliseconds
// the stack of `stop_watch` is empty now, so trying to `popDelta` will throw an error (intentional by design)
assertThrows(() => stop_watch.popDelta())

Constructors

Properties

stack: number[] = []

the stack in which we push timestamps.

time: (() => number)

a function that returns the current time

Methods

  • push the current time into the stack, and get the time elapsed since the last push. if this is the first push, then the returned value will be undefined.

    Returns undefined | number

  • get the time elapsed since the most recent push into the time stack, and also pop.

    Returns number

    Error this function will throw an error if the time stack was already empty. this is intentional, since it would hint that you are using this method non-deterministically, and thus incorrectly.

  • preview the time elapsed since the most recent push into the time stack, without popping. if there is nothing in the time stack, then an undefined will be returned.

    Returns undefined | number