2

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

I can run the whole code in terminal using node db.js command 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.

5 Answers 5

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();
});
Sign up to request clarification or add additional context in comments.

4 Comments

Would that take into account asynchronous nodejs approach? (e.g. if we have console.time('name') and then Part 1 of the code execute asynchronously - it might just 'pass trough' and hit the next console.timeEnd('name') which could provide false (lower) time than what actually takes to execute Part 1, or is really waiting in sequence for Part 1 to finish)?
To do that, you would have to do the timeEnd in the asynchronous callback.
@connexo - Do you have example of timeEnd in the asynchronous callback?
Added an example with the timeEnd in the callback.
1

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

2 Comments

How to put a value of console.timeEnd('part1'); into a variable so that can be used later?
Unfortunately you cannot. timeEnd() returns undefined.
0

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.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.