测量代码执行时间的 process.hrtime() 方法返回数组,其中包括当前的 high-resolution 实时 [秒,纳秒]。我们通过提供第一个 process.hrtime() 调用返回的时间作为第二个 process.hrtime() 调用中的参数来测量代码执行时间。
process.hrtime() 的优点是它测量时间非常准确,执行时间不到一毫秒。
用法:
process.hrtime([time])
参数:此方法接受如上所述的单个参数,如下所述。
- time:时间是一个可选参数,它必须是前一个进程的结果。hrtime() 调用与当前时间不同。
返回类型:它返回一个 2 个整数的数组。 1. int 包含秒,2. int 包含纳秒。这些时间与过去的任意时间相关,与一天中的时间无关。
范例1:
Javascript
// Implement the function..
var hrTime = process.hrtime()
// Time in millisecond...
console.log("Time in millisecond is:", hrTime[0] * 1000 + hrTime[1] / 1000000)
输出:
Time in millisecond is: 218394926745.5
范例2:
Javascript
// Create a variable and call the process.hrtime() function.
var start_time = process.hrtime();
// Print the Start time:
console.log("Start Time:",start_time);
// Make the add function
setTimeout(function(){
// Create two variable
var a = '40',
b = '50';
// Print the Addition result:
console.log("Add of two number is:",(a - 0) + (b - 0));
// Create a variable and call the second process.hrtime()
// function and pass the start time as parameter.
var end_time = process.hrtime(start_time);
// Print the Execution time.
console.log("End Time:",end_time);
}, 1000);
输出:这意味着从开始到结束的时间为 1 秒和 8779100 纳秒。
Start Time:[ 682340, 452477300 ] Add of two number is:90 End Time:[ 1, 8779100 ]
范例3:
Javascript
// Create a variable and call the process.hrtime() function.
var start_time = process.hrtime();
// Print the Start time:
console.log("Start Time:",start_time);
// Make the add function
setTimeout(function(){
console.log("Execution time will be calculated"+
" for printing this message....");
// Create a variable and call the second process.hrtime()
// function and pass the start time as.
var end_time = process.hrtime(start_time);
// Print the Execution time.
console.log("End Time:",end_time);
}, 1000);
输出:这意味着从开始到结束的时间为 1 秒和 10987200 纳秒。
Start Time:[ 682865, 516565300 ] Execution time will be calculated for printing this message.... End Time:[ 1, 10987200 ]
参考资料:https://nodejs.org/api/process.html#process_process_hrtime_time
相关用法
- Node.js process.nextTick()用法及代码示例
- Node.js GM solarize()用法及代码示例
- Node.js MySQL Max()用法及代码示例
- Lodash _.method()用法及代码示例
- Node.js Http2ServerRequest.method用法及代码示例
- Node.js http.IncomingMessage.method用法及代码示例
- Collect.js toArray()用法及代码示例
- Javascript RegExp toString()用法及代码示例
- Tensorflow.js tf.Sequential.evaluate()用法及代码示例
- Node.js URLSearchParams.has()用法及代码示例
- JavaScript Math cosh()用法及代码示例
- Node.js hmac.update()用法及代码示例
- jQWidgets jqxFormattedInput val()用法及代码示例
- HTML DOM isEqualNode()用法及代码示例
- JavaScript Date toLocaleTimeString()用法及代码示例
- Tensorflow.js tf.Tensor.buffer()用法及代码示例
注:本文由纯净天空筛选整理自_sh_pallavi大神的英文原创作品 Node.js process.hrtime( ) Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。