How to Speed Test a JavaScript Function

As JavaScript developers, we often focus on what works, but not always on how fast it works. Whether you're optimizing a loop-heavy function, comparing multiple algorithms, or just curious — knowing how much time a function takes to run can be incredibly useful.In this tutorial, we’ll create a simple JavaScript speed test utility to measure the execution time of any function.

🧠 Why Measure Function Speed?

Here are a few solid reasons to track execution time:✅ To identify bottlenecks in your app✅ To compare different approaches (e.g., loop vs. map)✅ To ensure performance before shipping production code✅ Just to geek out and learn 😄 

🛠️ The speedTest Function

Let’s build a reusable JavaScript function that accepts:a function to testthe number of times it should runand logs the total & average time 
function speedTest(fn, iterations = 1) {
 const start = performance.now(); for (let i = 0; i < iterations; i++) {
   fn();
 } const end = performance.now();
 const totalTime = end - start;
 const avgTime = totalTime / iterations; console.log(`Total time for ${iterations} runs: ${totalTime.toFixed(4)} ms`);
 console.log(`Average time per run: ${avgTime.toFixed(4)} ms`);
}
 

How to Use It

Let’s say you want to test how fast this loop runs:
function myTask() {
 let total = 0;
 for (let i = 0; i < 1000000; i++) {
   total += i;
 }
}
 
Now run it like this:
speedTest(myTask, 50);
 
This will run your myTask function 50 times and print:
Total time for 50 runs: 42.5431 ms
Average time per run: 0.8509 ms
 

🧪 Compare Two Functions

function slowTask() {
 for (let i = 0; i < 1e7; i++) {}
}function fastTask() {
 for (let i = 0; i < 1e5; i++) {}
}speedTest(slowTask, 10);
speedTest(fastTask, 10);
 
he logs will clearly show the difference in total and average execution time.

Bonus: For Async Functions

If you want to test asynchronous functions (e.g., API calls, setTimeout), here’s an async version:
async function speedTestAsync(fn, iterations = 1) {
 const start = performance.now(); for (let i = 0; i < iterations; i++) {
   await fn();
 } const end = performance.now();
 const totalTime = end - start;
 const avgTime = totalTime / iterations; console.log(`Total async time: ${totalTime.toFixed(4)} ms`);
 console.log(`Avg async time: ${avgTime.toFixed(4)} ms`);
}
 
Example:
async function waitTask() {
 return new Promise(resolve => setTimeout(resolve, 10));
}speedTestAsync(waitTask, 5);
 

🧠 Final Thoughts

Using performance.now() gives you high-resolution timing accurate to microseconds. This little utility can be a life-saver when you're debugging, benchmarking, or optimizing your code.You can even build a UI version of this if you're working on an online code editor or performance playground.