测量查询在NodeJS中运行所需的时间

k10s72fa  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(94)

我有一个简单的nodejs程序来测试查询性能,但我有一个问题,我有一个查询数组,当我循环它们并测量它们的时间时,第二个总是比第一个快,比如说我有查询A和B,如果数组看起来像这样[A,B],B会更快,但如果我将顺序改为[B,A],A会更快,但是单独运行它们(比如只有A或B的列表)或者在psql中运行,我发现它们几乎都有相同的结果。这里是代码。
index.js

const { Client } = require('pg');
const queryPref = require('./src/QueryPref');

require('dotenv').config();

(async ()=> await queryPref())();

queryPref.js

const { Client } = require('pg');

const queries = [
  {
    'queryStr': 'SELECT * FROM tabluno where user_name = $1',
    'options': ['08544f75d007ae439925bb21fe48c64c'],
  },
  {
    'queryStr': 'SELECT * FROM tabluno2 where user_name = $1',
    'options': ['f67a10e60fde706bb6c5948374b385e5'],
  },
]

function initClient() {
  console.log('opening a new connection');
  const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'indexing-is-really-hard',
    password: process.env.DB_PASSWORD,
    port: 5432 // default port for postgres
  });

  return client;
}

async function queryPref() {
  for(const query of queries) {
    let pool = new Client({
      user: 'postgres',
      host: 'localhost',
      database: 'indexing-is-really-hard',
      password: process.env.DB_PASSWORD,
      port: 5432, // default port for postgres
    });

    await pool.connect();
    await pool.query('SELECT 1');

    let avg = 0;
    for(let i = 0; i < 1000; i++)    {
      const start = performance.now();
      await pool.query(query.queryStr, query.options)
      const end = performance.now();
      avg += end - start;
    }
    avg /= 1000;

    console.log(`${query.queryStr} took an avg of ${avg.toFixed(3)}ms`)

    pool.end();
    pool = null;
  }
}

module.exports = queryPref;

正如你所看到的,我试图为每个查询初始化一个新的客户端,但它似乎什么也没做。
我试过使用连接池而不是客户端,但得到了相同的结果(第二个总是更快)。我也试过用客户端和池来测量1000多个查询的平均值,但还是得到了同样的结果。
编辑:results from nodejs app.
results from psql

uklbhaso

uklbhaso1#

在for循环中,你可以这样计算:

const startTime =  Date.now();
const timeTaken = Date.now() - startTime;

并在for循环外部的公共变量中添加时间Taken。

相关问题