window.performance.now()在nodejs中等价?

时间:2014-04-11 04:03:05

标签: javascript node.js navigation-timing-api

我认为问题很简单。

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

现在我只是使用: -

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

但是,我读到window.performance.now()比使用日期要准确得多,因为它定义了here

8 个答案:

答案 0 :(得分:48)

节点v8.5.0添加了Performance Timing API,其中包含performance#now(),例如

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

console.log('performance', performance.now());

答案 1 :(得分:37)

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

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

更新:如果您愿意,present套餐(可通过npm install present提供)可在hrtime附近提供一些糖。

答案 2 :(得分:28)

这是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”的内容

答案 3 :(得分:14)

怎么样?

console.time('FooTimer');
// do the work
console.timeEnd('FooTimer');

答案 4 :(得分:2)

这是一个带有process.hrtime()的手稿版本,基于NextLocal's回答:

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());

答案 5 :(得分:2)

process.uptime()


<块引用>

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

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

示例:测量 For 循环执行时间


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);

示例输出


enter image description here

答案 6 :(得分:0)

总结并避免使用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());

答案 7 :(得分:-1)