简体   繁体   English

JavaScript - 如何测量代码每个部分的执行时间

[英]JavaScript - how to measure execution time for each part of a code

JS code for connecting to DB and getting data is bellow.用于连接数据库和获取数据的 JS 代码如下。

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:我可以使用node db.js命令在终端中运行整个代码并测量总执行时间,但我想测量每个代码块执行所需的时间(以毫秒为单位):

# 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.谢谢。

You can use console.time('name') and console.timeEnd('name') to measure time between 2 places in your code. 您可以使用console.time('name')console.timeEnd('name')来测量代码中两个位置之间的时间。

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. 使用console.time(String str)启动一个命名计时器,并使用console.timeEnd(String str)结束测量并在控制台中输出时间。

 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". 如果您的问题实际上是“如何知道代码的哪一部分是sloooow”。 Tool that makes such a thing is named "profiler". 做这种事情的工具称为“探查器”。

NodeJS has integrated profiler that can be attached to your IDE(like Inteliji Webstorm ) NodeJS具有集成的探查器,可以将其附加到您的IDE(例如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. 或者,您可以搜索连接到V8探查器的专用软件包(例如v8-profiler ),并绘制图表/用其他一些软件包/自己的代码填充表格。

You can use built-in nodejs perf_hooks. 您可以使用内置的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`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM