nodejs-tw / ama

Ask me anything!
MIT License
31 stars 1 forks source link

如何使用 async_hooks 計算每個 async function 花費時間? #29

Open s1hon opened 6 years ago

s1hon commented 6 years ago

不知道這邊有沒有了解 async_hooks 的大大.... 最近遇到了一些問題想要來這邊請教一下

以下是我的程式碼:

const async_hooks = require('async_hooks')
const fs = require('fs')
const util = require('util')

let indent = 0

function debug(...args) {
  fs.writeSync(1, `${util.format(...args)}\n`)
}

function getIndent(n) {
  return ' '.repeat(n);
}

class MyAsyncCallbacks {
  init(asyncId, type, triggerAsyncId, resource) {
    this[asyncId] = Date.now()
    debug(`${getIndent(indent)}INIT:   ${asyncId} by ${triggerAsyncId}, ${type}, ${resource}`)
  }
  destroy(asyncId) {
    debug(`${getIndent(indent)}DESTRO: ${asyncId}`)
  }
  before(asyncId) {
    debug(`${getIndent(indent)}BEFORE: ${asyncId}`)
    indent += 2
  }
  after(asyncId) {
    indent -= 2
    debug(`${getIndent(indent)}AFTER:  ${asyncId} (${Date.now() - this[asyncId]})`)
  }
  promiseResolve(asyncId) {
    debug(`${getIndent(indent)}PROMIS: ${asyncId} (${Date.now() - this[asyncId]})`)
  }
}
const hook = async_hooks.createHook(new MyAsyncCallbacks()).enable()

fs.writeSync(1, `${getIndent(indent)}>>> Start.....\n`)
setTimeout(() => {
  fs.writeSync(1, `${getIndent(indent)}>>> I'm the setTimeout!\n`)
  new Promise((resolve) => resolve('RESOLVE RETURN')).then((a) => {
    fs.writeSync(1, `${getIndent(indent)}RETURN: ${a}\n`)
  })
}, 3000)
fs.writeSync(1, `${getIndent(indent)}>>> End.....\n`)

我目前是用 this[asyncId] = Date.now() 去存每個 hook 的時間 但是這種方式好像有點髒.....有人有更好的想法嗎?