w3resource

JavaScript: Get the number of times a function executed per second

JavaScript fundamental (ES6 Syntax): Exercise-218 with Solution

Write a JavaScript program to get the number of times a function executed per second. HZ is the unit for hertz, the unit of frequency defined as one cycle per second.

  • Use performance.now() to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function iterations times.
  • Return the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed.
  • Omit the second argument, iterations, to use the default of 100 iterations.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const hz = (fn, iterations = 100) => {
  const before = performance.now();
  for (let i = 0; i < iterations; i++) fn();
  return (1000 * iterations) / (performance.now() - before);
};
// 10,000 element array
const numbers = Array(10000)
  .fill()
  .map((_, i) => i);

// Test functions with the same goal: sum up the elements in the array
const sumReduce = () => numbers.reduce((acc, n) => acc + n, 0);
const sumForLoop = () => {
  let sum = 0;
  for (let i = 0; i < numbers.length; i++) sum += numbers[i];
  return sum;
};

// sumForLoop` is nearly 10 times faster
console.log(Math.round(hz(sumReduce)));
console.log(Math.round(hz(sumForLoop)));

Sample Output:

3584
2688

Flowchart:

flowchart: Get the number of times a function executed per second

Live Demo:

See the Pen javascript-fundamental-exercise-218 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to check if the given number falls within the given range.
Next: Write a JavaScript program to calculate the Hamming distance between two values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

Parse an HTTP Cookie header string and return an object of all cookie name-value pairs

Example:

const parseCookie = str =>
  str
    .split(';')
    .map(v => v.split('='))
    .reduce((acc, v) => {
      acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
      return acc;
    }, {});
console.log(parseCookie('foo=bar; equation=E%3Dmc%5E2')); // { foo: 'bar', equation: 'E=mc^2' } 

Output:

[object Object] {
  equation: "E=mc^2",
  foo: "bar"
} 

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook