📜  Node.js console.time() 方法

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

Node.js console.time() 方法

console.time() 方法是 Node.js 的控制台类。它用于启动一个计时器,用于计算一段代码或函数所花费的时间。方法console.timeEnd()用于停止计时器并将经过的时间(以毫秒为单位)输出到标准输出。计时器可以精确到亚毫秒。

句法

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