30秒学会 JavaScript 片段 · 2020年2月24日

30秒学会 JavaScript 片段 – timeTaken

Measures the time taken by a function to execute.

Use console.time() and console.timeEnd() to measure the difference between the start and end times to determine how long the callback took to execute.

代码片段

const timeTaken = callback => {
  console.time('timeTaken');
  const r = callback();
  console.timeEnd('timeTaken');
  return r;
};

使用样例

timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms