首页 > 解决方案 > 如何测试 Node + Postgres 的速度

问题描述

我正在循环中对数据库中的 1 行执行简单的更新请求。我使用库'pg-native'。

function testPostgres(){
    const moment = require('moment-timezone')
    const Client = require('pg-native')
    const client = new Client()
    client.connect('postgres://postgres:postgres@host:5432/postgres', function(err) {
        if(err) throw err

        const moment1 = moment()
        for (let i = 0; i < 1000; i++) {
            let rows = client.querySync('update json_test set data = data || \'{"SkillChance": 1}\', count =count+1 where id =$1',[1])

        }
        const moment2 = moment()
        const diff = moment2.diff(moment1, 'seconds')
        console.log(diff) //

    })
}

此代码(1000 次更新)在 14 秒内执行。Node + Mongoose 捆绑包的类似操作(更新)可在 1 秒内完成。我在做 Postgres 有什么问题?

PS我了解实际项目中不使用同步操作。我仅将 querySync 用于速度测试。

标签: node.jspostgresql

解决方案


尝试使用Promise.all并行运行查询,它应该可以帮助您减少执行时间。

async function testPostgres() {
  const moment = require('moment-timezone')
  const Client = require('pg-native')
  const client = new Client()
  await new Promise((resolve, reject) => {
    client.connect('postgres://postgres:postgres@host:5432/postgres', (err) => {
      if (err) reject(err);
      else resolve()
    })
  })

  const arrayOf1000 = new Array(1000).fill(0)
  const moment1 = moment()

  await Promise.all(arrayOf1000.map(() =>
    client.query('update json_test set data = data || \'{"SkillChance": 1}\', count =count+1 where id =$1', [1])
  ))


  const moment2 = moment()
  const diff = moment2.diff(moment1, 'seconds')
  console.log(diff) //
}

推荐阅读