Skip to content

Instantly share code, notes, and snippets.

@shuizhongyueming
Created April 16, 2023 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuizhongyueming/07e2acf112066003988a01ec576cd3a9 to your computer and use it in GitHub Desktop.
Save shuizhongyueming/07e2acf112066003988a01ec576cd3a9 to your computer and use it in GitHub Desktop.
analytics execution time for code block
/**
# 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