當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Node.js console.time()用法及代碼示例


console.time()方法是Node.js的控製台類。它用於啟動計時器,該計時器用於計算一段代碼或函數所花費的時間。方法console.timeEnd()用於停止計時器並將經過的時間(以毫秒為單位)輸出到stdout。計時器可以精確到sub-millisecond。

用法

console.time( label )

參數:此方法接受可以在方法中作為參數傳遞的單個參數標簽,如果未傳遞標簽,則默認標簽將自動提供給方法。對於不同的函數或代碼段,標簽可以不同。


以下示例說明了Node.js中console.time()方法的用法方式:

範例1:

// Node.js program to demonstrate the 
// console.time() method 
  
// Sample function 
function addCount() { 
  // Variable declaration 
  var sum = 0; 
  
  for (var i = 1; i < 100000; i++) { 
    // Adding i to the sum variable 
    sum += i; 
  } 
  
  // Return sum value 
  return sum; 
} 
  
// Starts the timer 
console.time(); 
  
// Function call 
addCount(); 
  
// Ends the timer and print the time 
// taken by the piece of code 
console.timeEnd();

輸出:

default:8.760ms

範例2:

// Node.js program to demonstrate the 
// console.time() method 
  
// Sample function 
function addCount() { 
  // Variable declaration 
  var sum = 0; 
  for (var i = 1; i < 100000; i++) { 
    // Adding i to the sum variable 
    sum += i; 
  } 
  return sum; // returning sum 
} 
  
var timetaken = "Time taken by addCount function"; 
  
// Starts the timer. The label value is timetaken 
console.time(timetaken); 
  
addCount(); // function call 
  
// Ends the timer and print the time 
// taken by the piece of code 
console.timeEnd(timetaken);

輸出:

Time taken by addCount function:7.380ms

範例3:此示例同時將不同的標簽用於不同的函數。

// Node.js program to demonstrate the 
// console.time() method 
  
// Sample function 
function addCount() { 
  var sum = 0; // Variable declaration 
  for (var i = 1; i < 100000; i++) { 
    sum += i; // Adding i to the sum variable 
  } 
  return sum; // returning sum 
} 
  
function countTime() { 
  var timetaken = "Time taken by addCount function"; 
  
  // Starts the timer, the label value is timetaken 
  console.time(timetaken); 
  
  console.log(addCount()); // function call 
  
  // Ends the timer and print the time 
  // taken by the piece of code 
  console.timeEnd(timetaken); 
} 
  
var label2 = "Time taken by countTime function"; 
  
// Starts the timer, the label value is label2 
console.time(label2); 
  
countTime(); // function call 
  
// Ends the timer and print the time 
// taken by the piece of code 
console.timeEnd(label2);

輸出:

4999950000
Time taken by addCount function:24.884ms
Time taken by countTime function:25.928ms

參考: https://nodejs.org/docs/latest-v11.x/api/console.html#console_console_time_label



相關用法


注:本文由純淨天空篩選整理自akshajjuneja9大神的英文原創作品 Node.js | console.time() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。