cm6-performance.ts 7.2 KB

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