profiling.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* oxlint-disable no-restricted-globals */
  2. import { type GenericComponentInstance, formatComponentName } from './component'
  3. import { devtoolsPerfEnd, devtoolsPerfStart } from './devtools'
  4. let supported: boolean
  5. let perf: Performance
  6. // To avoid the overhead of repeatedly calling Date.now(), we cache
  7. // and use the same timestamp for all event listeners attached in the same tick.
  8. let cachedNow: number = 0
  9. const p = /*@__PURE__*/ Promise.resolve()
  10. const getNow = () =>
  11. cachedNow ||
  12. (p.then(() => (cachedNow = 0)),
  13. (cachedNow = isSupported() ? perf.now() : Date.now()))
  14. /**
  15. * @internal
  16. */
  17. export function startMeasure(
  18. instance: GenericComponentInstance,
  19. type: string,
  20. ): void {
  21. if (instance.appContext.config.performance && isSupported()) {
  22. perf.mark(`vue-${type}-${instance.uid}`)
  23. }
  24. if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
  25. devtoolsPerfStart(instance, type, getNow())
  26. }
  27. }
  28. /**
  29. * @internal
  30. */
  31. export function endMeasure(
  32. instance: GenericComponentInstance,
  33. type: string,
  34. ): void {
  35. if (instance.appContext.config.performance && isSupported()) {
  36. const startTag = `vue-${type}-${instance.uid}`
  37. const endTag = startTag + `:end`
  38. const measureName = `<${formatComponentName(instance, instance.type)}> ${type}`
  39. perf.mark(endTag)
  40. perf.measure(measureName, startTag, endTag)
  41. perf.clearMeasures(measureName)
  42. perf.clearMarks(startTag)
  43. perf.clearMarks(endTag)
  44. }
  45. if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
  46. devtoolsPerfEnd(instance, type, getNow())
  47. }
  48. }
  49. function isSupported() {
  50. if (supported !== undefined) {
  51. return supported
  52. }
  53. if (typeof window !== 'undefined' && window.performance) {
  54. supported = true
  55. perf = window.performance
  56. } else {
  57. supported = false
  58. }
  59. return supported
  60. }