Измерить время процесса с помощью Node Js?

4

Я хотел бы сделать следующее:

console.time("processA");
for(let i; i < 10000; i++) {
// Just to simulate the process
}
console.timeEnd("processA");

но я хочу захватить время и использовать с ним собственный журнал.

Можно ли обрабатывать консольный вывод timeEnd?

Как измерить временной интервал процесса в nodejs?

Теги:
performance

4 ответа

6
Лучший ответ

Поскольку вы нацелены на nodejs, вы можете использовать process.hrtime как указано в документации

Метод process.hrtime() возвращает текущее высокое разрешение в реальном времени в массиве кортежей [секунды, наносекунды], где наносекунды - это оставшаяся часть реального времени, которая не может быть представлена с точностью до секунды.

Таким образом, вы можете измерить время с точностью до наносекунды, что не может сделать console.time, как вы можете видеть в своем примере console.time или разность Date измеряет 0 с.

Например:

const NS_PER_SEC = 1e9;
const MS_PER_NS = 1e-6
const time = process.hrtime();
for (let i; i < 10000; i++) {
  // Just to simulate the process
}
const diff = process.hrtime(time);
console.log('Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds');
console.log('Benchmark took ${ (diff[0] * NS_PER_SEC + diff[1])  * MS_PER_NS } milliseconds');
3
var startTime = new Date();
for(let i; i < 10000; i++) {
// Just to simulate the process
}
var endTime = new Date() - startTime;

Вы получите общее время, необходимое для завершения операции

  • 0
    Может быть, использовать моменты, чтобы вычесть время, может быть опция const startTime = moment (Date.now ()); // обработать const totalTime = moment (Date.now ()). substract (startTime);
0

Поскольку я использую таймеры в нескольких местах, я написал простой класс на основе ответа Алекса:

const t = new Timer('For Loop')
// your code
t.runtimeMs()     // => 1212.34
t.runtimeMsStr()  // => 'For Loop took 1232.34 milliseconds'

Вот код:

class Timer {
    // Automatically starts the timer
    constructor(name = 'Benchmark') {
        this.NS_PER_SEC = 1e9;
        this.MS_PER_NS = 1e-6
        this.name = name;
        this.startTime = process.hrtime();
    }

    // returns the time in ms since instantiation
    // can be called multiple times
    runtimeMs() {
        const diff = process.hrtime(this.startTime);
        return (diff[0] * this.NS_PER_SEC + diff[1]) * this.MS_PER_NS;
    }

    // retuns a string: the time in ms since instantiation
    runtimeMsStr() {
        return '${this.name} took ${this.runtimeMs()} milliseconds';
    }
}
0

См. Здесь https://alligator.io/js/console-time-timeend/

var begin=console.time('t');

for(let i; i < 100000; i++) {
// Just to simulate the process
}
var end= console.timeEnd('t');

var timeSpent=(end-begin) / 1000 + "secs";
  • 0
    end и begin не определены, timeSpent равен NaNsecs в конце

Ещё вопросы

Сообщество Overcoder
Наверх
Меню