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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。