Created
April 16, 2023 11:29
-
-
Save shuizhongyueming/07e2acf112066003988a01ec576cd3a9 to your computer and use it in GitHub Desktop.
analytics execution time for code block
This file contains 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
/** | |
# Usages: | |
pfv.start('some'); | |
// some code | |
// some code | |
pfv.end(); | |
pfv.check('ff', () => { | |
// some code | |
// some code | |
}); | |
pfv.dump(); // get performance of releated code | |
**/ | |
window.pfv = (() => { | |
// {tag: { context, costTime, callTimes, startTime }} | |
const performance = typeof tt !== 'undefined' ? tt.getPerformance() : window.performance; | |
const map = new Map(); | |
let contextStack = []; | |
const getTag = tag => { | |
if (!map.has(tag)) { | |
map.set(tag, { | |
deep: contextStack.length, | |
context: contextStack[0], | |
costTime: 0, | |
callTimes: 0, | |
startTime: performance.now() | |
}); | |
} | |
return map.get(tag); | |
}; | |
const endCurrentTag = () => { | |
const tag = contextStack.shift(); | |
const d = map.get(tag); | |
d.callTimes++; | |
d.costTime += performance.now() - d.startTime; | |
}; | |
return { | |
track(tag, f) { | |
this.start(tag); | |
f(); | |
this.end(); | |
}, | |
start(tag) { | |
contextStack.unshift(tag); | |
getTag(tag).startTime = performance.now(); | |
}, | |
end(tag) { | |
if (tag) { | |
while(contextStack.length > 0 && contextStack[0] !== tag) { | |
endCurrentTag(); | |
} | |
endCurrentTag(); | |
} else { | |
endCurrentTag(); | |
} | |
}, | |
dump() { | |
let str = ''; | |
[...map.entries()].forEach(([tag, d]) => { | |
str += `${'='.repeat(d.deep)}${tag}: ${d.callTimes}, ${d.costTime}\n`; | |
}); | |
console.log(str); | |
contextStack = []; | |
map.clear(); | |
}, | |
data() { | |
return map | |
} | |
} | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment