Làm thế nào để đo thời gian của các hoạt động không đồng bộ trong Nodejs?
Làm thế nào để đo thời gian của các hoạt động không đồng bộ trong Nodejs?
Có ba mức, từ đơn giản đến chuyên sâu.
Dùng performance.now() (độ phân giải cao, đơn điệu) thay vì Date.now():
import { performance } from 'node:perf_hooks';
const start = performance.now();
const rows = await db.query('SELECT * FROM orders WHERE user_id = $1', [id]);
console.log(`query mất ${(performance.now() - start).toFixed(1)}ms`);
Hoặc dùng performance.mark/measure để gom số liệu và quan sát bằng PerformanceObserver:
import { performance, PerformanceObserver } from 'node:perf_hooks';
new PerformanceObserver((list) => {
for (const e of list.getEntries()) console.log(e.name, e.duration.toFixed(1), 'ms');
}).observe({ entryTypes: ['measure'] });
performance.mark('fetch-start');
await fetch('https://api.example.com/data');
performance.mark('fetch-end');
performance.measure('fetch api', 'fetch-start', 'fetch-end');
performance.timerify(fn) bọc một hàm để tự đo mỗi lần gọi. console.time('x') / console.timeEnd('x') tiện khi debug nhanh.
prom-client).Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.