Created
June 14, 2023 04:58
-
-
Save alexreardon/f1e3f4ff6cff883d0dd7817b4712b202 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const interactions: number[][] = []; | |
function sum(values: number[]) { | |
return values.reduce((acc, current) => acc + current, 0); | |
} | |
function average(values: number[]): number { | |
if (!values.length) { | |
return 0; | |
} | |
return sum(values) / values.length; | |
} | |
function getPercentile({ | |
values, | |
percentile, | |
}: { | |
values: number[]; | |
percentile: number; | |
}) { | |
const bestToWorst = [...values].sort((a, b) => a - b); | |
const pIndex = Math.floor((values.length / 100) * percentile); | |
return bestToWorst[pIndex]; | |
} | |
/* eslint-disable @repo/internal/dom-events/no-unsafe-event-listeners */ | |
window.addEventListener('mousedown', function onMouseDown() { | |
const longTasks: number[] = []; | |
console.log('long-task', 'mousedown'); | |
console.log('long-task', 'start monitoring'); | |
const observer = new PerformanceObserver(function perfObserver(list) { | |
list.getEntries().forEach(entry => { | |
if (entry.entryType === 'longtask') { | |
longTasks.push(entry.duration); | |
} | |
}); | |
}); | |
observer.observe({ entryTypes: ['longtask'] }); | |
setTimeout(() => { | |
observer.disconnect(); | |
interactions.push(longTasks); | |
console.log('long-task: interaction result', { | |
numberOfLongTasks: longTasks.length, | |
combinedDuration: sum(longTasks), | |
}); | |
const sums = interactions.map(interaction => sum(interaction)); | |
console.log('long-task', 'total long task duration per interaction', { | |
interactionCount: interactions.length, | |
average: average(sums), | |
p50: getPercentile({ values: sums, percentile: 50 }), | |
p90: getPercentile({ values: sums, percentile: 90 }), | |
p95: getPercentile({ values: sums, percentile: 95 }), | |
p99: getPercentile({ values: sums, percentile: 99 }), | |
}); | |
const individuals = interactions.flat(); | |
console.log('long-task', 'individual long tasks', { | |
interactionCount: interactions.length, | |
longTaskCount: individuals.length, | |
average: average(individuals), | |
p50: getPercentile({ values: individuals, percentile: 50 }), | |
p90: getPercentile({ values: individuals, percentile: 90 }), | |
p95: getPercentile({ values: individuals, percentile: 95 }), | |
p99: getPercentile({ values: individuals, percentile: 99 }), | |
}); | |
}, 1000); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment