Is there are any implementations of stopwatch in TypeScript?

Viewed 6379

I would like to run performance measurement for some critical functions on the website written on TypeScript. I'm wondering if there is any implementation of stopwatch similar to .NET System.Diagnostics.Stopwatch class in TypeScript?

4 Answers

Building off of basarat's answer above, this is already built in to console.

console.time('myTask');
// code to time here
console.timeLog('myTask');
console.timeEnd('myTask');

Since the OP asked specifically for something similar to .NET's Stopwatch, the @tsdotnet/stopwatch package might be a good option.

First, install package in your npm project: npm i @tsdotnet/stopwatch

Code example:

import Stopwatch from "@tsdotnet/stopwatch"

(async () => {
const stopwatch = Stopwatch.startNew();

    // Simulates a delay of 1000 milliseconds.
    await new Promise(r => setTimeout(r, 1000));

    console.log(stopwatch.elapsedMilliseconds);
})();

Please, notice that your tsconfig.json needs to be targeting at least es2015 due to the use of promises in this example. This is not a requirement because of @tsdotnet/stopwatch.

Related