Profiler.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* eslint-disable
  2. no-unused-vars,
  3. */
  4. // TODO: This file was created by bulk-decaffeinate.
  5. // Fix any style issues and re-enable lint.
  6. /*
  7. * decaffeinate suggestions:
  8. * DS101: Remove unnecessary use of Array.from
  9. * DS102: Remove unnecessary code created because of implicit returns
  10. * DS206: Consider reworking classes to avoid initClass
  11. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  12. */
  13. import Settings from '@overleaf/settings'
  14. import logger from '@overleaf/logger'
  15. import metrics from '@overleaf/metrics'
  16. const LOG_CUTOFF_TIME = 1000
  17. const deltaMs = function (ta, tb) {
  18. const nanoSeconds = (ta[0] - tb[0]) * 1e9 + (ta[1] - tb[1])
  19. const milliSeconds = Math.floor(nanoSeconds * 1e-6)
  20. return milliSeconds
  21. }
  22. export class Profiler {
  23. constructor(name, args) {
  24. this.name = name
  25. this.args = args
  26. this.t0 = this.t = process.hrtime()
  27. this.start = new Date()
  28. this.updateTimes = []
  29. }
  30. log(label) {
  31. const t1 = process.hrtime()
  32. const dtMilliSec = deltaMs(t1, this.t)
  33. this.t = t1
  34. this.updateTimes.push([label, dtMilliSec]) // timings in ms
  35. return this // make it chainable
  36. }
  37. end(message) {
  38. const totalTime = deltaMs(this.t, this.t0)
  39. // record the update times in metrics
  40. for (const update of Array.from(this.updateTimes)) {
  41. metrics.timing(`profile.${this.name}.${update[0]}`, update[1])
  42. }
  43. if (totalTime > LOG_CUTOFF_TIME) {
  44. // log anything greater than cutoff
  45. const args = {}
  46. for (const k in this.args) {
  47. const v = this.args[k]
  48. args[k] = v
  49. }
  50. args.updateTimes = this.updateTimes
  51. args.start = this.start
  52. args.end = new Date()
  53. logger.debug(args, this.name)
  54. }
  55. return totalTime
  56. }
  57. getTimeDelta() {
  58. const lastIdx = this.updateTimes.length - 1
  59. if (lastIdx >= 0) {
  60. return this.updateTimes[lastIdx][1]
  61. } else {
  62. return 0
  63. }
  64. }
  65. wrap(label, fn) {
  66. // create a wrapped function which calls profile.log(label) before continuing execution
  67. const newFn = (...args) => {
  68. this.log(label)
  69. return fn(...Array.from(args || []))
  70. }
  71. return newFn
  72. }
  73. }