以前有写过一个使用speedscope 的简单说明,以下是一个使用另外一个工具进行火焰图分析的简单说明
环境准备
- 项目结构
├── app.js
├── package.json
└── yarn.lock
- 代码说明
app.js
//app.js
const express = require(‘express‘);
const console = require(‘console‘);
const levenshtein = require(‘fast-levenshtein‘);
var arr=[];
const HOW_OBVIOUS_THE_FLAME_GRAPH_SHOULD_BE_ON_SCALE_1_TO_100 = 10;
?
const someFakeModule = (function someFakeModule () {
return {
calculateStringDistance (a, b) {
return levenshtein.get(a, b, {
useCollator: true
})
}
}
})()
?
const app = express();
?
app.get(‘/‘, (req, res) => {
res.send(`
<h2>Take a look at the network tab in devtools</h2>
<script>
function loops(func) {
return func().then(_ => setTimeout(loops, 20, func))
}
loops(_ => fetch(‘api/tick‘))
</script>\
`)
});
?
app.get(‘/api/tick‘, (req, res) => {
arr.push({name:‘Shubham‘});
Promise.resolve(‘asynchronous flow will make our stacktrace more realistic‘.repeat(HOW_OBVIOUS_THE_FLAME_GRAPH_SHOULD_BE_ON_SCALE_1_TO_100))
.then(text => {
const randomText =Math.random().toString(32).repeat(HOW_OBVIOUS_THE_FLAME_GRAPH_SHOULD_BE_ON_SCALE_1_TO_100)
return someFakeModule.calculateStringDistance(text, randomText)
})
.then(result => res.end(`result: ${result}, ${arr.length}`))
});
?
app.get(‘/api/end‘, () => process.exit());
?
app.listen(8080, () => {
console.log(`go to http://localhost:8080/ to generate traffic`)
});
pacakge.json
{
"name": "nodejs-flame-graph",
"version": "1.0.0",
"main": "app.js",
"license": "MIT",
"scripts": {
"start": "node --perf-basic-prof-only-functions app.js",
"pprof":"node --prof app.js",
"flame":"node --prof-process --preprocess -j isolate*.log | flamebearer"
},
"dependencies": {
"express": "^4.14.1",
"fast-levenshtein": "^2.0.6"
},
"devDependencies": {
"flamebearer": "^1.1.3"
}
}
启动&&测试
- 启动集成prof
yarn pprof
- 一些压力测试
ab -n 2000 -c 100 http://localhost:8080/api/tick
- 生成火焰图
yarn flame
- 效果
可以看出calculateStringDistance
占用是比较高的 - 说明
对于火焰图的生成使用了flamebearer 工具,实际上perf 也是一个很强大的工具,提供nodejs 官方也介绍了如何使用perf 进行分析
参考资料
https://nodejs.org/en/docs/guides/diagnostics-flamegraph/
https://github.com/mapbox/flamebearer
https://nodejs.org/uk/docs/guides/simple-profiling/
原文地址:https://www.cnblogs.com/rongfengliang/p/12128876.html
时间: 2024-10-09 12:54:02