Profiler.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const logger = require('@overleaf/logger')
  2. function deltaMs(ta, tb) {
  3. const nanoSeconds = (ta[0] - tb[0]) * 1e9 + (ta[1] - tb[1])
  4. const milliSeconds = Math.floor(nanoSeconds * 1e-6)
  5. return milliSeconds
  6. }
  7. class Profiler {
  8. LOG_CUTOFF_TIME = 15 * 1000
  9. LOG_SYNC_CUTOFF_TIME = 1000
  10. constructor(name, args) {
  11. this.name = name
  12. this.args = args
  13. this.t0 = this.t = process.hrtime()
  14. this.start = new Date()
  15. this.updateTimes = []
  16. this.totalSyncTime = 0
  17. }
  18. log(label, options = {}) {
  19. const t1 = process.hrtime()
  20. const dtMilliSec = deltaMs(t1, this.t)
  21. this.t = t1
  22. this.totalSyncTime += options.sync ? dtMilliSec : 0
  23. this.updateTimes.push([label, dtMilliSec]) // timings in ms
  24. return this // make it chainable
  25. }
  26. end() {
  27. const totalTime = deltaMs(this.t, this.t0)
  28. const exceedsCutoff = totalTime > this.LOG_CUTOFF_TIME
  29. const exceedsSyncCutoff = this.totalSyncTime > this.LOG_SYNC_CUTOFF_TIME
  30. if (exceedsCutoff || exceedsSyncCutoff) {
  31. // log anything greater than cutoffs
  32. const args = {}
  33. for (const k in this.args) {
  34. const v = this.args[k]
  35. args[k] = v
  36. }
  37. args.updateTimes = this.updateTimes
  38. args.start = this.start
  39. args.end = new Date()
  40. args.status = { exceedsCutoff, exceedsSyncCutoff }
  41. logger.warn(args, this.name)
  42. }
  43. return totalTime
  44. }
  45. }
  46. module.exports = Profiler