102

我认为这个问题是直截了当的。

我正在寻找类似于 nodejs V8 引擎中的 window.performance.now() 的东西。

现在我只是在使用:-

var now = Date.now();
//do some processing..
console.log("time elapsed:", Date.now() - now);

但是,我读到 window.performance.now() 比使用日期准确得多,因为这里定义了什么。

4

8 回答 8

142

Node v8.5.0 增加了Performance Timing API,其中包括performance#now(),例如

const {
  performance
} = require('perf_hooks');

console.log('performance', performance.now());
于 2017-09-30T12:43:42.720 回答
61

我只想提一下,作者给出的浏览器中计时 API 的偏好的三个原因似乎并不直接适用于节点情况,第四个,Javscript 时间的不准确,引用了 2008 年的一篇文章,我强烈警告不要依赖关于 Javascript 性能细节的旧材料,特别是考虑到最近一轮所有引擎为支持“HTML5”应用程序所做的性能改进。

但是,在回答您的问题时,您应该查看process.hrtime()

更新:如果您愿意,该present软件包(可通过 获取npm install present)提供一些糖。hrtime

注意:Node 8.5.0 版本开始,可以使用performance.now()

于 2014-04-11T04:33:31.220 回答
30

process.hrtime()这是返回毫秒而不是微秒的快捷方式:

function clock(start) {
    if ( !start ) return process.hrtime();
    var end = process.hrtime(start);
    return Math.round((end[0]*1000) + (end[1]/1000000));
}

用法:

var start = clock();
// do some processing that takes time
var duration = clock(start);
console.log("Took "+duration+"ms");

将输出类似“Took 200ms”的内容

于 2016-01-24T00:02:02.497 回答
17

关于什么?

console.time('FooTimer');
// do the work
console.timeEnd('FooTimer');
于 2015-07-27T13:51:44.570 回答
2

进程正常运行时间()


“该方法返回process.uptime() 当前 Node.js 进程已运行的秒数。

返回值包括几分之一秒。用于Math.floor()获得 整秒。”

示例:测量循环执行时间


const nemo = ['nemo'];

function findNemo(array) {
  
  let start_time = process.uptime();

  for (let iteration = 0; iteration < array.length; iteration++) {
     if (array[iteration] === 'nemo') {
        console.log("Found Nemo");
     }
  }

  let end_time = process.uptime();

  console.log("For loop took this much time: ", end_time - start_time);
}

findNemo(nemo);

示例输出


在此处输入图像描述

于 2021-04-24T05:44:30.360 回答
1

这是基于NextLocal 的回答的带有process.hrtime()的 Typescript 版本:

class Benchmark {

    private start = process.hrtime();

    public elapsed(): number {
        const end = process.hrtime(this.start);
        return Math.round((end[0] * 1000) + (end[1] / 1000000));
    }
}

export = Benchmark;

用法:

import Benchmark = require("./benchmark");

const benchmark = new Benchmark();

console.log(benchmark.elapsed());
于 2017-02-15T18:02:24.123 回答
1

总结和避免使用perf_hooks

const performance = {
        now: function(start) {
            if ( !start ) return process.hrtime();
            var end = process.hrtime(start);
            return Math.round((end[0]*1000) + (end[1]/1000000));
        }
    }
console.log('performance', performance.now());
于 2019-04-17T19:13:06.640 回答
0

此方法在 nodejs 的 8.5.0 版本中出现https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_measurement_apis

于 2020-07-09T00:49:27.223 回答