Explain Codes LogoExplain Codes Logo

How to measure time taken by a function to execute

javascript
performance
timing
functions
Anton ShumikhinbyAnton Shumikhin·Aug 23, 2024
TLDR

Dive straight into microsecond accurate timings with JavaScript's performance.now(). Seize timestamps before and after your function to calculate its execution time:

let start = performance.now(); // Start the clock! yourFunction(); // Unleash the function let duration = performance.now() - start; // Stop the clock! console.log(`Executed in ${duration}ms`); // Time's up!

duration mirrors the milliseconds your function spent executing.

Deep dive into performance measurement

Precision matters: Choosing the right tool for the job

While performance.now() is considered the gold standard for precise timings, the reasons are manifold. Date.getTime() taps the number of milliseconds since the Unix Epoch. However, system clock alterations can impair its accuracy.

Casual timing with the console

For less demanding scenarios, console.time(label) and console.timeEnd(label) tackle basic timing with ease. Beware of label inconsistencies:

console.time('MyFunctionPerformance'); // Tick-tock on the clock myFunction(); // Release the code kraken console.timeEnd('MyFunctionPerformance'); // Ding! Your time's up!

Note: Their use in production-grade data is contested due to their lower precision standards.

Mind the platform: Browser and server-side timing

While performance.now() enjoys comprehensive browser support, server-side(Node.js) timings require the perf_hooks module:

const { performance } = require('perf_hooks'); // Special delivery for Node.js

Left-field landmines

The Date object can pose pitfalls in performance timing scenarios. Such drawbacks range from negative durations to errant timestamps. So, for accurate measurements stick with **performance.now()**.

Future-ready performance timing

Callback from the past: Polyfills

Pin down legacy browser compatibility with polyfills. They ensure your performance.now() and UserTiming API calls don't fall deaf on older ears.

Performance profiling: A Detective's tool

Web developers can also exploit in-built browser profiling tools. They hand you execution insights without spurring codebase modifications - a cornucopia in a performance-geared world.

Real-world face-offs

Lessons are often learnt the hard way. Applications like Gmail and Google Sheets have at times fallen prey to timing errors ensuing from Date. It's fairly evident why **performance.now()** holds its ground.

Shining the spotlight on usages

Function execution time tracking

Performance tuning rides on the ability to pinpoint potential lags. Reliable and granular tracking can log even the smallest improvements.

Measuring loop durations

Loops often dictate data manipulation or processing operations. Monitoring their execution time exposes performance bottlenecks and areas of improvement.

Advanced performance tracking techniques

User Timing API: Your toolbox for customization

Explore UserTiming API's intricate timings. It layers your marks and measures and expands the performance interface:

performance.mark('A'); myFunction(); performance.mark('B'); performance.measure('MyFunctionPeriod', 'A', 'B');

Delve into these markings with performance.getEntriesByName('MyFunctionPeriod').

Taming the server-side: Node.js precision techniques

Node.js offers process.hrtime(), providing nanosecond precision. It's like splitting hairs - digitally!

let start = process.hrtime(); // Time travel begins! someServerSideFunction(); // Node.js code panda on the loose! let diff = process.hrtime(start); // Congratulations, traveller! You did it in ${diff[0] * 1e9 + diff[1]} nanoseconds! console.log(`Function executed in ${diff[0] * 1e9 + diff[1]} nanoseconds`); // Share travel tales!