📜  如何测量函数使用 JavaScript 执行所花费的时间?

📅  最后修改于: 2022-05-13 01:58:09.985000             🧑  作者: Mango

如何测量函数使用 JavaScript 执行所花费的时间?

方法一:使用performance.now()方法:性能接口的now()方法在程序中无论何时被调用都会返回一个高分辨率的时间戳。时间可以通过获取函数之前的开始时间和函数之后的结束时间然后减去它们来测量。这给出了函数经过的时间。

句法:

start = performance.now();
function_to_call();
 end = performance.now();

例子:



      

    
        How to measure time taken by a function
        to execute using JavaScript?
    

  

    

        GeeksforGeeks     

                    How to measure time taken by a function         to execute using JavaScript?                 

        Click on the button to measure the time         taken by the function. The output would         be displayed on the console.     

                                               

输出:

  • 在点击按钮之前:
    表现
  • 点击按钮后:
    性能输出

方法二:使用console.time() 方法: Console 对象的time() 和timeEnd() 方法可以作为一个计时器来测量这两个方法之间所用的时间。它需要一个标签参数,可用于区分多个计时器。每当调用 timeEnd() 方法时,计时器就会停止并将时间输出提供给控制台。

句法:

console.time('label');
function_to_call();
console.timeEnd('label');

例子:



      

    
        How to measure time taken by a function
        to execute using JavaScript?
    

  

    

        GeeksforGeeks     

                    How to measure time taken by a function         to execute using JavaScript?                 

        Click on the button to measure the time         taken by the function. The output would         be displayed on the console.     

                                               

输出:

  • 在点击按钮之前:
    控制台结束
  • 点击按钮后:
    控制台输出