Golang性能分析的简单示例,用于培训目的。

huangapple go评论77阅读模式
英文:

Golang profiling simple example for training purposes

问题

我正在我的公司进行Go培训,我想以最好的方式展示pprof包。我觉得我的示例不足以简单地展示pprof的强大之处。我想只使用Go标准库。代码应该给我一个更简单的调用图,显示一些瓶颈。

我的当前工作流程如下:

  1. 在Web服务器中包含pprof。
  2. 运行Web服务器(它将收集30秒钟的数据(默认))。
  3. 运行一些curl命令到Web服务器。
  4. 展示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

Golang性能分析的简单示例,用于培训目的。

仅针对handler()函数的Pprof

Golang性能分析的简单示例,用于培训目的。


<details>
<summary>英文:</summary>

I&#39;m doing Go training in my company and I want to present in best way pprof package. I think that My example isn&#39;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&#39;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 (
    	&quot;fmt&quot;
    	&quot;net/http&quot;
    	_ &quot;net/http/pprof&quot;
    )
    
    func handler(w http.ResponseWriter, r *http.Request) {
    	for i := 0; i &lt; 100000000; i++ {
    		w.Write([]byte(fmt.Sprintf(&quot;%d - %d, &quot;, i, i)))
    	}
    }
    
    func main() {
    	http.HandleFunc(&quot;/&quot;, handler)
    	http.ListenAndServe(&quot;:8080&quot;, 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 &lt; 100000; i++ {
		s += strconv.Itoa(i)
	}
	w.Write([]byte(s))
}

huangapple
  • 本文由 发表于 2015年11月6日 00:11:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/33549505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定