cm6-performance.ts 8.0 KB

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