|
| 1 | +import * as marky from 'marky'; |
| 2 | + |
| 3 | +const fmt = (time) => `${Math.round(time * 100) / 100}ms`; |
| 4 | + |
| 5 | +const measure = (name, fn) => { |
| 6 | + marky.mark(name); |
| 7 | + fn(); |
| 8 | + const performanceMeasure = marky.stop(name); |
| 9 | + return performanceMeasure; |
| 10 | +}; |
| 11 | + |
| 12 | +const benchmark = ({ name, description, setup, teardown, task, runs }) => { |
| 13 | + return new Promise((resolve) => { |
| 14 | + const performanceMeasures = []; |
| 15 | + let i = 0; |
| 16 | + |
| 17 | + setup(); |
| 18 | + const first = measure('first', task); |
| 19 | + teardown(); |
| 20 | + |
| 21 | + const done = () => { |
| 22 | + const mean = performanceMeasures.reduce((sum, performanceMeasure) => { |
| 23 | + return sum + performanceMeasure.duration; |
| 24 | + }, 0) / runs; |
| 25 | + |
| 26 | + const firstDuration = fmt(first.duration); |
| 27 | + const meanDuration = fmt(mean); |
| 28 | + |
| 29 | + console.log(`First: ${firstDuration}`); |
| 30 | + console.log(`Mean: ${meanDuration}`); |
| 31 | + console.groupEnd(); |
| 32 | + resolve(mean); |
| 33 | + }; |
| 34 | + |
| 35 | + const a = () => { |
| 36 | + setup(); |
| 37 | + window.requestAnimationFrame(b); |
| 38 | + }; |
| 39 | + |
| 40 | + const b = () => { |
| 41 | + performanceMeasures.push(measure('mean', task)); |
| 42 | + window.requestAnimationFrame(c); |
| 43 | + }; |
| 44 | + |
| 45 | + const c = () => { |
| 46 | + teardown(); |
| 47 | + window.requestAnimationFrame(d); |
| 48 | + }; |
| 49 | + |
| 50 | + const d = () => { |
| 51 | + i += 1; |
| 52 | + if (i < runs) { |
| 53 | + window.requestAnimationFrame(a); |
| 54 | + } else { |
| 55 | + window.requestAnimationFrame(done); |
| 56 | + } |
| 57 | + }; |
| 58 | + |
| 59 | + console.group(); |
| 60 | + console.log(`[benchmark] ${name}: ${description}`); |
| 61 | + window.requestAnimationFrame(a); |
| 62 | + }); |
| 63 | +}; |
| 64 | + |
| 65 | +module.exports = benchmark; |
0 commit comments