cm6-performance.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. function clearCM6Perf(type: string) {
  145. switch (type) {
  146. case 'measure':
  147. performance.clearMeasures(TIMER_MEASURE_NAME)
  148. performance.clearMarks(TIMER_START_NAME)
  149. performance.clearMarks(TIMER_END_NAME)
  150. break
  151. case 'dom':
  152. performance.clearMarks(TIMER_DOM_UPDATE_NAME)
  153. break
  154. case 'keypress':
  155. performance.clearMeasures(TIMER_KEYPRESS_MEASURE_NAME)
  156. break
  157. }
  158. }
  159. // clear performance measures and marks when switching between Source and Rich Text
  160. window.addEventListener('editor:visual-switch', () => {
  161. clearCM6Perf('measure')
  162. clearCM6Perf('dom')
  163. clearCM6Perf('keypress')
  164. })
  165. export function reportCM6Perf() {
  166. // Get entries triggered by keystrokes
  167. const cm6Entries = performance.getEntriesByName(
  168. TIMER_MEASURE_NAME,
  169. 'measure'
  170. ) as PerformanceMeasure[]
  171. clearCM6Perf('measure')
  172. const inputEvents = cm6Entries.filter(({ detail }) =>
  173. isInputOrDelete(detail.userEventType)
  174. )
  175. const inputDurations = inputEvents
  176. .map(({ duration }) => duration)
  177. .sort((a, b) => a - b)
  178. const max = round(calculateMax(inputDurations), 2)
  179. const mean = round(calculateMean(inputDurations), 2)
  180. const median = round(calculateMedian(inputDurations), 2)
  181. const ninetyFifthPercentile = round(
  182. calculate95thPercentile(inputDurations),
  183. 2
  184. )
  185. const maxUserEventsBetweenDomUpdates = calculateMax(
  186. inputEvents.map(e => e.detail.userEventsSinceDomUpdateCount)
  187. )
  188. const grammarly = grammarlyExtensionPresent()
  189. const sessionLength = Math.floor((Date.now() - sessionStart) / 1000) // In seconds
  190. const memory = performanceMemorySupport ? measureMemoryUsage() : null
  191. // Get entries for keypress counts between DOM updates
  192. const domUpdateEntries = performance.getEntriesByName(
  193. TIMER_DOM_UPDATE_NAME,
  194. 'mark'
  195. ) as PerformanceMark[]
  196. clearCM6Perf('dom')
  197. let lags = 0
  198. let nonLags = 0
  199. let longestLag = 0
  200. let totalKeypressCount = 0
  201. for (const entry of domUpdateEntries) {
  202. const keypressCount = entry.detail.keypressesSinceDomUpdateCount
  203. if (keypressCount === 1) {
  204. ++nonLags
  205. } else if (keypressCount > 1) {
  206. ++lags
  207. }
  208. if (keypressCount > longestLag) {
  209. longestLag = keypressCount
  210. }
  211. totalKeypressCount += keypressCount
  212. }
  213. const meanLagsPerMeasure = round(lags / (lags + nonLags), 4)
  214. const meanKeypressesPerMeasure = round(
  215. totalKeypressCount / (lags + nonLags),
  216. 4
  217. )
  218. // Get entries triggered by keystrokes
  219. const keypressPaintEntries = performance.getEntriesByName(
  220. TIMER_KEYPRESS_MEASURE_NAME,
  221. 'measure'
  222. ) as PerformanceMeasure[]
  223. const keypressPaintDurations = keypressPaintEntries.map(
  224. ({ duration }) => duration
  225. )
  226. const meanKeypressPaint = round(calculateMean(keypressPaintDurations), 2)
  227. clearCM6Perf('keypress')
  228. let longTasks = null
  229. // Get long task entries (Chromium-based browsers only at time of writing)
  230. if (performanceLongtaskSupported) {
  231. longTasks = longTaskSinceLastReportCount
  232. longTaskSinceLastReportCount = 0
  233. }
  234. const release = getMeta('ol-ExposedSettings')?.sentryRelease || null
  235. return {
  236. max,
  237. mean,
  238. median,
  239. ninetyFifthPercentile,
  240. maxUserEventsBetweenDomUpdates,
  241. docLength: latestDocLength,
  242. numberOfEntries: inputDurations.length,
  243. grammarly,
  244. sessionLength,
  245. memory,
  246. lags,
  247. nonLags,
  248. longestLag,
  249. meanLagsPerMeasure,
  250. meanKeypressesPerMeasure,
  251. meanKeypressPaint,
  252. longTasks,
  253. release,
  254. }
  255. }
  256. window._reportCM6Perf = () => {
  257. console.log(reportCM6Perf())
  258. }