Created
March 1, 2024 06:10
-
-
Save leite08/1d5d2dd3643c0097ff9ddd678ac89276 to your computer and use it in GitHub Desktop.
Typescript code to time creating connections with Postgres
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Client } from "pg"; | |
type Result = { | |
connect: number; | |
close: number; | |
total: number; | |
}; | |
let results: Result[] = []; | |
async function query() { | |
const client = new Client({ | |
host: "localhost", | |
database: "db", | |
user: "admin", | |
password: "admin", | |
port: 5432, | |
}); | |
const before = Date.now(); | |
await client.connect(); | |
const midway = Date.now(); | |
await client.end(); | |
const after = Date.now(); | |
const connect = midway - before; | |
const close = after - midway; | |
const total = after - before; | |
results.push({ connect, close, total }); | |
} | |
function consolidateAndLogResults() { | |
const consolidated = results.reduce( | |
(acc, curr) => { | |
acc.connect += curr.connect; | |
acc.close += curr.close; | |
acc.total += curr.total; | |
return acc; | |
}, | |
{ connect: 0, close: 0, total: 0 } | |
); | |
const connect = consolidated.connect / results.length; | |
const close = consolidated.close / results.length; | |
const total = consolidated.total / results.length; | |
console.log(`Average connect: ${connect}ms`); | |
console.log(`Average close: ${close}ms`); | |
console.log(`Average total: ${total}ms`); | |
} | |
async function main() { | |
const count = 1000; | |
const beforeSync = Date.now(); | |
console.log(`Running ${count} connections Synchronously...`); | |
for (let i = 0; i < count; i++) await query(); | |
consolidateAndLogResults(); | |
console.log(`Done in ${Date.now() - beforeSync}ms`); | |
console.log(``); | |
results = []; | |
const beforeAsync = Date.now(); | |
console.log(`Running ${count} connections Aynchronously...`); | |
await Promise.all([...Array(count)].map(() => query())); | |
consolidateAndLogResults(); | |
console.log(`Done in ${Date.now() - beforeAsync}ms`); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment