最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - JavaScript - how to measure execution time for each part of a code - Stack Overflow

programmeradmin0浏览0评论

JS code for connecting to DB and getting data is bellow.

I can run the whole code in terminal using node db.js mand and measure total execution time but would like is to measure how long it takes for each chunk of code to execute in milliseconds:

# Part 1:
var mysql = require('mysql');

# Part 2:
var connection = mysql.createConnection({
    host: '...',
    user: '...',
    password: '...'
    port : ...
    database: '...'
});

# Part 3:
connection.connect(function(err) {
  if (err) throw err;
  connection.query("SELECT * FROM table", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
  connection.end();
});

How to measure each part above?

Thanks.

JS code for connecting to DB and getting data is bellow.

I can run the whole code in terminal using node db.js mand and measure total execution time but would like is to measure how long it takes for each chunk of code to execute in milliseconds:

# Part 1:
var mysql = require('mysql');

# Part 2:
var connection = mysql.createConnection({
    host: '...',
    user: '...',
    password: '...'
    port : ...
    database: '...'
});

# Part 3:
connection.connect(function(err) {
  if (err) throw err;
  connection.query("SELECT * FROM table", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
  connection.end();
});

How to measure each part above?

Thanks.

Share Improve this question asked Oct 10, 2018 at 18:08 JoeJoe 13.2k40 gold badges123 silver badges202 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

You can use console.time('name') and console.timeEnd('name') to measure time between 2 places in your code.

would look something like this:

console.time('part1')   //start timer for part 1.
var mysql = require('mysql');
console.timeEnd('part1')    //end timer 1 and log how long it took.  

console.time('part2')   //start timer for part 2.
var connection = mysql.createConnection({
    host: '...',
    user: '...',
    password: '...'
    port : ...
    database: '...'
});
console.timeEnd('part2')    //end timer 2 and log how long it took. 

console.time('part3')   //start timer for part 3.
connection.connect(function(err) {
  if (err) throw err;
  connection.query("SELECT * FROM table", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
    console.timeEnd('part3')    //end timer 3 in the callback and log how long it took. 
  });
  connection.end();
});

Use console.time(String str) to start a named timer, and console.timeEnd(String str) to end measuring and ouput the time in the console.

function countToThousand(callback) {
  console.time('part1');
  let a = 0;
  for (var i = 0; i < 1000; i++) {
    a += i
  }
  callback(a)
}

function myCallback(a) {
  console.log('a is '+a);
  console.timeEnd('part1')
}

countToThousand(myCallback)

// etc

In case your question is actually "how to know what part of code is sloooow". Tool that makes such a thing is named "profiler".

NodeJS has integrated profiler that can be attached to your IDE(like Inteliji Webstorm)

Or you can search for dedicated package(like v8-profiler) that connects to V8 profiler and draw charts/fill the table with some other package/your own code.

You can use built-in nodejs perf_hooks. For example:

// Dependencies
const { performance, PerformanceObserver } = require('perf_hooks');



performance.mark('start part1');
console.time('part1')   //start timer for part 1.
var mysql = require('mysql');
console.timeEnd('part1')    //end timer 1 and log how long it took.  
performance.mark('end part1');

performance.mark('start part2');
console.time('part2')   //start timer for part 2.
var connection = mysql.createConnection({
  host: '...',
  user: '...',
  password: '...'
    port: ...
  database: '...'
});
console.timeEnd('part2')    //end timer 2 and log how long it took. 
performance.mark('end part2');

performance.mark('start part3');
console.time('part3')   //start timer for part 3.
connection.connect(function (err) {
  if (err) throw err;
  connection.query("SELECT * FROM table", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
    console.timeEnd('part3')    //end timer 3 in the callback and log how long it took. 
    performance.mark('end part3');

    // Create observer to log out all the measurements
    const obs = new PerformanceObserver((list) => {
      // called once. list contains three items
      const measurements = list.getEntriesByType('measure');
      measurements.forEach((measurement) => {
        console.log(`${measurement.name} ${measurement.duration}`);
      });
    });
    obs.observe({ entryTypes: ['measure'] });

    // Gather all the measurements
    performance.measure('Beggining to end', 'start part1', 'end part3'); // Measure whole function
    performance.measure('Part1', 'start part1', 'end part1'); // Measure the part1
    performance.measure('Part2', 'start part2', 'end part2'); // Measure the part2
    performance.measure('Part3', 'start part3', 'end part3'); // Measure the part3

  });
  connection.end();
});

use this method

 const startTime =new Date().getTime();

//part of the code

const endTime = new Date().getTime();
console.log(`time taken=> ${(endTime - startTime)/1000} seconds`);
发布评论

评论列表(0)

  1. 暂无评论