英文:
Golang profiling simple example for training purposes
问题
我正在我的公司进行Go培训,我想以最好的方式展示pprof包。我觉得我的示例不足以简单地展示pprof的强大之处。我想只使用Go标准库。代码应该给我一个更简单的调用图,显示一些瓶颈。
我的当前工作流程如下:
- 在Web服务器中包含pprof。
- 运行Web服务器(它将收集30秒钟的数据(默认))。
- 运行一些curl命令到Web服务器。
- 展示pprof图形。
我的代码如下所示:
package main
import (
"fmt"
"net/http"
_ "net/http/pprof"
)
func handler(w http.ResponseWriter, r *http.Request) {
for i := 0; i < 100000000; i++ {
w.Write([]byte(fmt.Sprintf("%d - %d, ", i, i)))
}
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
未进行过滤的Pprof
仅针对handler()函数的Pprof
<details>
<summary>英文:</summary>
I'm doing Go training in my company and I want to present in best way pprof package. I think that My example isn't good enough to simply present power of pprof. I want to use only go std library. Code should give me
simplier call graph with some bottleneck.
My current workflow is as below:
1. include pprof in webserver
2. run webserver (it'll gather data for 30 seconds (default))
3. run some curl shots to webserver
4. present pprof graphs
My code looks like below:
package main
import (
"fmt"
"net/http"
_ "net/http/pprof"
)
func handler(w http.ResponseWriter, r *http.Request) {
for i := 0; i < 100000000; i++ {
w.Write([]byte(fmt.Sprintf("%d - %d, ", i, i)))
}
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
### Pprof without filtering
[![ppfof all][1]][1]
### Pprof for handler() function only
[![enter image description here][2]][2]
[1]: http://i.stack.imgur.com/PtXhQ.jpg
[2]: http://i.stack.imgur.com/lmCos.jpg
</details>
# 答案1
**得分**: 1
字符串拼接怎么样?它在我的机器上产生了一个相当线性的图形。此外,这是一个很好的方式来教导人们为什么应该通过将字符串附加到`[]byte`而不是拼接字符串来构建字符串,以避免创建大量的垃圾。
```go
func handler(w http.ResponseWriter, r *http.Request) {
var s string
for i := 0; i < 100000; i++ {
s += strconv.Itoa(i)
}
w.Write([]byte(s))
}
英文:
How about string concatenation? It produces a fairly linear graph on my machine. Besides, this is a good way to teach people why they should build strings by appenting to a []byte
rather than concatenating strings, creating tonnes of garbage.
func handler(w http.ResponseWriter, r *http.Request) {
var s string
for i := 0; i < 100000; i++ {
s += strconv.Itoa(i)
}
w.Write([]byte(s))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论