JavaScript 如何测量函数执行时间
在这篇文章中我们将使用JavaScript来测量函数执行所需要的时间。我们有两种方法来测量函数执行所需的时间:
- 使用performance.now()方法
- 使用console.time()方法
方法1:使用performance.now()方法
performance接口的now()方法在程序执行过程中每次调用时返回一个高分辨率的时间戳。通过在函数之前获取开始时间和函数之后获取结束时间并相减,可以测量出函数的执行时间。
语法:
start = performance.now();
function_to_call();
end = performance.now();
示例: 此示例解释了上述使用的方法。
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to measure time taken by a function
to execute using JavaScript?
</b>
<p>
Click on the button to measure the time
taken by the function. The output would
be displayed on the console.
</p>
<button onclick="measurePerformance()">
Click to check
</button>
<script type="text/javascript">
function measurePerformance() {
start = performance.now();
exampleFunction();
end = performance.now();
timeTaken = end - start;
console.log("Function took " +
timeTaken + " milliseconds");
}
function exampleFunction() {
for (i = 0; i < 1000; i++) {
console.log('Hello Geeks');
}
}
</script>
输出:
方法2:使用console.time()方法
Console对象的 time() 和 timeEnd() 方法可以用作计时器,用来测量这两个方法之间所需的时间。它接受一个标签参数,可以用来区分多个计时器。每当调用timeEnd()方法时,计时器就会停止,并将时间输出给控制台。
语法:
console.time('label');
function_to_call();
console.timeEnd('label');
示例: 这个示例解释了上面的方法。
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to measure time taken by a function
to execute using JavaScript?
</b>
<p>
Click on the button to measure the time
taken by the function. The output would
be displayed on the console.
</p>
<button onclick="measurePerformance()">
Click to check
</button>
<script type="text/javascript">
function measurePerformance() {
console.time('function1');
exampleFunction();
console.timeEnd('function1');
}
function exampleFunction() {
for(i= 0;i <1000; i++) {
console.log('Hello Geeks');
}
}
</script>
输出: