Measure the Executable Time
To measure the executable time of a method in JavaScript, use one of these standard approaches: performance.now()
, console.time()
/ console.timeEnd()
, or Date.now()
for millisecond accuracy.[2][3][5][7]
Using performance.now()
This method gives high-resolution timing, precise to fractions of a millisecond.
const start = performance.now();
myMethod(); // The method to measure
const end = performance.now();
console.log(`myMethod took ${end - start}ms`);
Using console.time()
This is a quick way to log timing directly to the console.
console.time("myMethod");
myMethod();
console.timeEnd("myMethod"); // Logs: myMethod: X ms
Using Date.now()
Best for less precise needs or if you want to work with raw integer milliseconds.
const start = Date.now();
myMethod();
const end = Date.now();
console.log(`myMethod took ${end - start}ms`);
Summary
- Use
performance.now()
for most accurate measurement. console.time()
/console.timeEnd()
work great for quick profiling.Date.now()
ornew Date().getTime()
are simple but less accurate.
All approaches work in TypeScript as they are provided by the underlying JavaScript engine.[7][9]