cm6-performance.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import { Transaction } from '@codemirror/state'
  2. import { EditorView } from '@codemirror/view'
  3. import { round } from 'lodash'
  4. import grammarlyExtensionPresent from '../shared/utils/grammarly'
  5. const TIMER_START_NAME = 'CM6-BeforeUpdate'
  6. const TIMER_END_NAME = 'CM6-AfterUpdate'
  7. const TIMER_DOM_UPDATE_NAME = 'CM6-DomUpdate'
  8. const TIMER_MEASURE_NAME = 'CM6-Update'
  9. let latestDocLength = 0
  10. const sessionStart = Date.now()
  11. let performanceOptionsSupport = false
  12. // Check that performance.mark and performance.measure accept an options object
  13. try {
  14. const testMarkName = 'featureTestMark'
  15. performance.mark(testMarkName, {
  16. startTime: performance.now(),
  17. detail: { test: 1 },
  18. })
  19. performance.clearMarks(testMarkName)
  20. const testMeasureName = 'featureTestMeasure'
  21. performance.measure(testMeasureName, {
  22. start: performance.now(),
  23. detail: { test: 1 },
  24. })
  25. performance.clearMeasures(testMeasureName)
  26. performanceOptionsSupport = true
  27. } catch (e) {}
  28. let performanceMemorySupport = false
  29. function measureMemoryUsage() {
  30. // @ts-ignore
  31. return performance.memory.usedJSHeapSize
  32. }
  33. try {
  34. if ('memory' in window.performance) {
  35. measureMemoryUsage()
  36. performanceMemorySupport = true
  37. }
  38. } catch (e) {}
  39. function isInputOrDelete(userEventType: string | undefined) {
  40. return (
  41. !!userEventType && ['input', 'delete'].includes(userEventType.split('.')[0])
  42. )
  43. }
  44. // "keypress" is not strictly accurate; what we really mean is a user-initiated
  45. // event that either inserts or deletes exactly one character. This corresponds
  46. // to CM6 user event types input.type, delete.forward or delete.backward
  47. function isKeypress(userEventType: string | undefined) {
  48. return (
  49. !!userEventType &&
  50. ['input.type', 'delete.forward', 'delete.backward'].includes(userEventType)
  51. )
  52. }
  53. export function timedDispatch() {
  54. let userEventsSinceDomUpdateCount = 0
  55. let keypressesSinceDomUpdateCount = 0
  56. return (
  57. view: EditorView,
  58. tr: Transaction,
  59. dispatchFn: (tr: Transaction) => void
  60. ) => {
  61. if (!performanceOptionsSupport) {
  62. dispatchFn(tr)
  63. return
  64. }
  65. performance.mark(TIMER_START_NAME)
  66. dispatchFn(tr)
  67. performance.mark(TIMER_END_NAME)
  68. const userEventType = tr.annotation(Transaction.userEvent)
  69. if (isInputOrDelete(userEventType)) {
  70. ++userEventsSinceDomUpdateCount
  71. if (isKeypress(userEventType)) {
  72. ++keypressesSinceDomUpdateCount
  73. }
  74. performance.measure(TIMER_MEASURE_NAME, {
  75. start: TIMER_START_NAME,
  76. end: TIMER_END_NAME,
  77. detail: { userEventType, userEventsSinceDomUpdateCount },
  78. })
  79. // The `key` property ensures that the measurement task is only run once
  80. // per measure phase
  81. view.requestMeasure({
  82. key: 'inputEventCounter',
  83. read() {
  84. performance.mark(TIMER_DOM_UPDATE_NAME, {
  85. detail: { keypressesSinceDomUpdateCount },
  86. })
  87. userEventsSinceDomUpdateCount = 0
  88. keypressesSinceDomUpdateCount = 0
  89. },
  90. })
  91. }
  92. latestDocLength = tr.state.doc.length
  93. }
  94. }
  95. function calculateMean(durations: number[]) {
  96. if (durations.length === 0) return 0
  97. const sum = durations.reduce((acc, entry) => acc + entry, 0)
  98. return sum / durations.length
  99. }
  100. function calculateMedian(sortedDurations: number[]) {
  101. if (sortedDurations.length === 0) return 0
  102. const middle = Math.floor(sortedDurations.length / 2)
  103. if (sortedDurations.length % 2 === 0) {
  104. return (sortedDurations[middle - 1] + sortedDurations[middle]) / 2
  105. }
  106. return sortedDurations[middle]
  107. }
  108. function calculate95thPercentile(sortedDurations: number[]) {
  109. if (sortedDurations.length === 0) return 0
  110. const index = Math.round((sortedDurations.length - 1) * 0.95)
  111. return sortedDurations[index]
  112. }
  113. function calculateMax(numbers: number[]) {
  114. return numbers.reduce((a, b) => Math.max(a, b), 0)
  115. }
  116. export function reportCM6Perf() {
  117. // Get entries triggered by keystrokes
  118. const cm6Entries = performance.getEntriesByName(
  119. TIMER_MEASURE_NAME,
  120. 'measure'
  121. ) as PerformanceMeasure[]
  122. performance.clearMeasures(TIMER_MEASURE_NAME)
  123. performance.clearMarks(TIMER_START_NAME)
  124. performance.clearMarks(TIMER_END_NAME)
  125. const inputEvents = cm6Entries.filter(({ detail }) =>
  126. isInputOrDelete(detail.userEventType)
  127. )
  128. const inputDurations = inputEvents
  129. .map(({ duration }) => duration)
  130. .sort((a, b) => a - b)
  131. const max = round(calculateMax(inputDurations), 2)
  132. const mean = round(calculateMean(inputDurations), 2)
  133. const median = round(calculateMedian(inputDurations), 2)
  134. const ninetyFifthPercentile = round(
  135. calculate95thPercentile(inputDurations),
  136. 2
  137. )
  138. const maxUserEventsBetweenDomUpdates = calculateMax(
  139. inputEvents.map(e => e.detail.userEventsSinceDomUpdateCount)
  140. )
  141. const grammarly = grammarlyExtensionPresent()
  142. const sessionLength = Math.floor((Date.now() - sessionStart) / 1000) // In seconds
  143. const memory = performanceMemorySupport ? measureMemoryUsage() : null
  144. // Get entries for keypress counts between DOM updates
  145. const domUpdateEntries = performance.getEntriesByName(
  146. TIMER_DOM_UPDATE_NAME,
  147. 'mark'
  148. ) as PerformanceMeasure[]
  149. performance.clearMarks(TIMER_DOM_UPDATE_NAME)
  150. let lags = 0
  151. let nonLags = 0
  152. let longestLag = 0
  153. let totalKeypressCount = 0
  154. for (const entry of domUpdateEntries) {
  155. const keypressCount = entry.detail.keypressesSinceDomUpdateCount
  156. if (keypressCount === 1) {
  157. ++nonLags
  158. } else if (keypressCount > 1) {
  159. ++lags
  160. }
  161. if (keypressCount > longestLag) {
  162. longestLag = keypressCount
  163. }
  164. totalKeypressCount += keypressCount
  165. }
  166. const meanLagsPerMeasure = round(lags / (lags + nonLags), 4)
  167. const meanKeypressesPerMeasure = round(
  168. totalKeypressCount / (lags + nonLags),
  169. 4
  170. )
  171. return {
  172. max,
  173. mean,
  174. median,
  175. ninetyFifthPercentile,
  176. maxUserEventsBetweenDomUpdates,
  177. docLength: latestDocLength,
  178. numberOfEntries: inputDurations.length,
  179. grammarly,
  180. sessionLength,
  181. memory,
  182. lags,
  183. nonLags,
  184. longestLag,
  185. meanLagsPerMeasure,
  186. meanKeypressesPerMeasure,
  187. }
  188. }
  189. window._reportCM6Perf = () => {
  190. console.log(reportCM6Perf())
  191. }