NodeJS MySQL:测量查询执行时间

t9aqgxwy  于 5个月前  发布在  Mysql
关注(0)|答案(4)|浏览(59)

我在一个共享托管平台上,想节流我的应用程序中的查询,这样如果总执行时间超过一定数量在一个可变的时间段,那么我可以使应用程序冷却,然后恢复以后。
要做到这一点,我想找出我的每个查询需要多长时间在真实的时间和管理它的应用程序内,而不是通过分析它的外部。
我在PHP中看到过这样的例子,在查询之前和之后记录时间(甚至phpMyAdmin也这样做),但这在NodeJS或任何异步运行查询的东西中都不起作用。
所以问题是:我如何在NodeJS中获得查询的实际执行时间?
作为参考,我使用此模块查询MySQL数据库:https://github.com/felixge/node-mysql/

svujldwt

svujldwt1#

一个选项是在查询之前和查询之后分别添加时间戳,并检查两者之间的差异,如下所示:

// get a timestamp before running the query
var pre_query = new Date().getTime();
// run the job
connection.query(query, function(err, rows, fields) {
  // get a timestamp after running the query
  var post_query = new Date().getTime();
  // calculate the duration in seconds
  var duration = (post_query - pre_query) / 1000;
});

字符串

irtuqstp

irtuqstp2#

console.time('100-elements');
for (let i = 0; i < 100; i++) {}
console.timeEnd('100-elements');
// prints 100-elements: 225.438ms

字符串

  • 标签必须是唯一的,并且与开始和结束时间相同 *

在nodejs中运行良好。
以下是nodejs文档

ctehm74n

ctehm74n3#

如果你使用的是rest API,那么你可以使用postman。在postman中运行查询,然后在部分的中间右侧查找Time:,如附件中的图像所示。

j2datikz

j2datikz4#

您可以使用
performance.now)搜索结果
用于测量查询执行时间的方法。使用console.time()也可以。但是performace.now()console.time()好得多。您可以如下使用它:

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

function add(a, b) {
    return a + b;
}

const start = performance.now();
add(1, 2);
const end = performance.now();
console.log(`Time taken to execute add function is ${end - start}ms.`);

字符串

相关问题