cm6-performance.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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: (trs: readonly Transaction[]) => void
  70. end: (trs: readonly 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 = (trs: readonly Transaction[]) => {
  79. const keypressStart = performance.now()
  80. trs.forEach(tr => {
  81. const userEventType = tr.annotation(Transaction.userEvent)
  82. if (isKeypress(userEventType)) {
  83. unpaintedKeypressStartTimes.push(keypressStart)
  84. }
  85. })
  86. performance.mark(TIMER_START_NAME)
  87. }
  88. const end = (trs: readonly Transaction[], view: EditorView) => {
  89. performance.mark(TIMER_END_NAME)
  90. let anyInputOrDelete = false
  91. trs.forEach(tr => {
  92. const userEventType = tr.annotation(Transaction.userEvent)
  93. if (isInputOrDelete(userEventType)) {
  94. anyInputOrDelete = true
  95. ++userEventsSinceDomUpdateCount
  96. if (isKeypress(userEventType)) {
  97. ++keypressesSinceDomUpdateCount
  98. }
  99. performance.measure(TIMER_MEASURE_NAME, {
  100. start: TIMER_START_NAME,
  101. end: TIMER_END_NAME,
  102. detail: { userEventType, userEventsSinceDomUpdateCount },
  103. })
  104. }
  105. })
  106. if (anyInputOrDelete) {
  107. // The `key` property ensures that the measurement task is only run once
  108. // per measure phase
  109. view.requestMeasure({
  110. key: 'inputEventCounter',
  111. read() {
  112. performance.mark(TIMER_DOM_UPDATE_NAME, {
  113. detail: { keypressesSinceDomUpdateCount },
  114. })
  115. userEventsSinceDomUpdateCount = 0
  116. keypressesSinceDomUpdateCount = 0
  117. const keypressEnd = performance.now()
  118. for (const keypressStart of unpaintedKeypressStartTimes) {
  119. performance.measure(TIMER_KEYPRESS_MEASURE_NAME, {
  120. start: keypressStart,
  121. end: keypressEnd,
  122. })
  123. }
  124. unpaintedKeypressStartTimes.length = 0
  125. },
  126. })
  127. }
  128. latestDocLength = trs[trs.length - 1].state.doc.length
  129. }
  130. return { start, end }
  131. }
  132. function calculateMean(durations: number[]) {
  133. if (durations.length === 0) return 0
  134. const sum = durations.reduce((acc, entry) => acc + entry, 0)
  135. return sum / durations.length
  136. }
  137. function calculateMedian(sortedDurations: number[]) {
  138. if (sortedDurations.length === 0) return 0
  139. const middle = Math.floor(sortedDurations.length / 2)
  140. if (sortedDurations.length % 2 === 0) {
  141. return (sortedDurations[middle - 1] + sortedDurations[middle]) / 2
  142. }
  143. return sortedDurations[middle]
  144. }
  145. function calculate95thPercentile(sortedDurations: number[]) {
  146. if (sortedDurations.length === 0) return 0
  147. const index = Math.round((sortedDurations.length - 1) * 0.95)
  148. return sortedDurations[index]
  149. }
  150. function calculateMax(numbers: number[]) {
  151. return numbers.reduce((a, b) => Math.max(a, b), 0)
  152. }
  153. function clearCM6Perf(type: string) {
  154. switch (type) {
  155. case 'measure':
  156. performance.clearMeasures(TIMER_MEASURE_NAME)
  157. performance.clearMarks(TIMER_START_NAME)
  158. performance.clearMarks(TIMER_END_NAME)
  159. break
  160. case 'dom':
  161. performance.clearMarks(TIMER_DOM_UPDATE_NAME)
  162. break
  163. case 'keypress':
  164. performance.clearMeasures(TIMER_KEYPRESS_MEASURE_NAME)
  165. break
  166. }
  167. }
  168. // clear performance measures and marks when switching between Source and Rich Text
  169. window.addEventListener('editor:visual-switch', () => {
  170. clearCM6Perf('measure')
  171. clearCM6Perf('dom')
  172. clearCM6Perf('keypress')
  173. })
  174. export function reportCM6Perf() {
  175. // Get entries triggered by keystrokes
  176. const cm6Entries = performance.getEntriesByName(
  177. TIMER_MEASURE_NAME,
  178. 'measure'
  179. ) as PerformanceMeasure[]
  180. clearCM6Perf('measure')
  181. const inputEvents = cm6Entries.filter(({ detail }) =>
  182. isInputOrDelete(detail.userEventType)
  183. )
  184. const inputDurations = inputEvents
  185. .map(({ duration }) => duration)
  186. .sort((a, b) => a - b)
  187. const max = round(calculateMax(inputDurations), 2)
  188. const mean = round(calculateMean(inputDurations), 2)
  189. const median = round(calculateMedian(inputDurations), 2)
  190. const ninetyFifthPercentile = round(
  191. calculate95thPercentile(inputDurations),
  192. 2
  193. )
  194. const maxUserEventsBetweenDomUpdates = calculateMax(
  195. inputEvents.map(e => e.detail.userEventsSinceDomUpdateCount)
  196. )
  197. const grammarly = grammarlyExtensionPresent()
  198. const sessionLength = Math.floor((Date.now() - sessionStart) / 1000) // In seconds
  199. const memory = performanceMemorySupport ? measureMemoryUsage() : null
  200. // Get entries for keypress counts between DOM updates
  201. const domUpdateEntries = performance.getEntriesByName(
  202. TIMER_DOM_UPDATE_NAME,
  203. 'mark'
  204. ) as PerformanceMark[]
  205. clearCM6Perf('dom')
  206. let lags = 0
  207. let nonLags = 0
  208. let longestLag = 0
  209. let totalKeypressCount = 0
  210. for (const entry of domUpdateEntries) {
  211. const keypressCount = entry.detail.keypressesSinceDomUpdateCount
  212. if (keypressCount === 1) {
  213. ++nonLags
  214. } else if (keypressCount > 1) {
  215. ++lags
  216. }
  217. if (keypressCount > longestLag) {
  218. longestLag = keypressCount
  219. }
  220. totalKeypressCount += keypressCount
  221. }
  222. const meanLagsPerMeasure = round(lags / (lags + nonLags), 4)
  223. const meanKeypressesPerMeasure = round(
  224. totalKeypressCount / (lags + nonLags),
  225. 4
  226. )
  227. // Get entries triggered by keystrokes
  228. const keypressPaintEntries = performance.getEntriesByName(
  229. TIMER_KEYPRESS_MEASURE_NAME,
  230. 'measure'
  231. ) as PerformanceMeasure[]
  232. const keypressPaintDurations = keypressPaintEntries.map(
  233. ({ duration }) => duration
  234. )
  235. const meanKeypressPaint = round(calculateMean(keypressPaintDurations), 2)
  236. clearCM6Perf('keypress')
  237. let longTasks = null
  238. // Get long task entries (Chromium-based browsers only at time of writing)
  239. if (performanceLongtaskSupported) {
  240. longTasks = longTaskSinceLastReportCount
  241. longTaskSinceLastReportCount = 0
  242. }
  243. const release = getMeta('ol-ExposedSettings')?.sentryRelease || null
  244. return {
  245. max,
  246. mean,
  247. median,
  248. ninetyFifthPercentile,
  249. maxUserEventsBetweenDomUpdates,
  250. docLength: latestDocLength,
  251. numberOfEntries: inputDurations.length,
  252. grammarly,
  253. sessionLength,
  254. memory,
  255. lags,
  256. nonLags,
  257. longestLag,
  258. meanLagsPerMeasure,
  259. meanKeypressesPerMeasure,
  260. meanKeypressPaint,
  261. longTasks,
  262. release,
  263. }
  264. }
  265. window._reportCM6Perf = () => {
  266. console.log(reportCM6Perf())
  267. }