Using Flamegraphs to perform performance analysis of Go programs

Source: Internet
Author: User
Tags sprintf stack trace statsd
February 28, 2018 performance problems are inherently unpredictable-and they always show their heads at the worst of times. To make things worse, many performance analysis tools are cold, complex, and downright confusing-the user experience of the most admired performance analysis tools, from ' valgrind ' and ' GDP '. ' Flamegraphs ' is a tool created by the Linux performance analysis guru Brendan Gegg to generate an SVG visualization layer on the general Linux performance Tracking dump, which brings some "warmth" to the complex process of locating and solving performance problems. In this article, we'll step-by-step the performance analysis of a simple Golang-written web application with ' flamegraphs '. # # Before you start, you can only perform performance analysis and optimization when you know your program has a performance problem. Premature performance optimization will not only waste your time in the present, but will slow you down if you have to refactor in the future, these carefully adjusted fragile code. # # Example Program we will use a small HTTP server to demonstrate that the server through ' get/ping ' exposes a healthcheck API. For visualization, we also included a small [STATSD] (https://www.datadoghq.com/blog/statsd/) client to record the latency of each request processed by the server. To keep it simple, our code only uses the Go standard library, but even if you're used to ' Gorilla/mux ' or other popular libraries, the code won't be too strange for you. ' Goimport ("FMT" "Log" "Net/http" "Strings" "Net" "Time")//SimpleClient is a thin statsd client.type simpleclient Stru CT {c net. Packetconn RA *net. udpaddr}//Newsimpleclient instantiates a new simpleclient instance which binds//to the provided UDP Address.func NewSimp Leclient (addr string) (*simpleclient, error) {c, err: = Net. Listenpacket ("UDP", ": 0") if err! = Nil {return nil, err} ra, err: = Net. RESOLVEUDPADDR ("UDP", addr) if err! = Nil {c.close () return nil, err} return &simpleclient{c:c, Ra:ra,}, nil}// Timing sends a STATSD Timing Call.func (sc *simpleclient) Timing (s string, D time. Duration, samplerate float64, tags map[string]string) error {return sc.send (Fmtstatstr (FMT). Sprintf ("%s:%d|ms", S, D/time.millisecond), tags),}func (SC *simpleclient) Send (s string) error {_, err: = sc.c. ( *net. Udpconn). WRITETOUDP ([]byte (s), sc.ra) if err! = Nil {return err} return Nil}func FMTSTATSTR (stat string, tags map[string]string) string {parts: = []string{} for K, V: = Range Tags {if v! = "" {parts = append (Parts, FMT. Sprintf ("%s:%s", K, V)}} return to FMT. Sprintf ("%s|%s", Stat, strings. Join (Parts, ","))}func Main () {stats, err: = Newsimpleclient ("localhost:6060") if err! = Nil {log. Fatal ("Could not start Stas client:", err)}//Add handlers to default Mux http. Handlefunc ("/ping", Pinghandler (stats)) s: = & http. server{Addr: ": 8080",} log. Fatal (S.listenandserve ())}func Pinghandler (S *simpleclient) http. handlerfunc{return func (w http. Responsewriter, R *http. Request) {st: = time. Now () defer func () {_ = s.timing ("Http.ping", time. Since (ST), 1.0, Nil)} () W.writeheader (200)} "# # # Install Profiling Tools The standard library of Go has built-in tools for diagnosing performance problems, and a rich and complete set of tools to embed the go simple and efficient runtime. If your app is using the default ' HTTP '. Defaultservemux ', then integrate ' pprof ' without additional code, simply add the following statement to your ' import ' header. "' Goimport (_" net/http/pprof ")" You can verify that your configuration is correct by starting the server and accessing ' debug/pprof ' in any browser. For our example application, the--pprof interface is exposed to ' localhost:8080/debug/pprof '. # # The job of generating flamegraph ' flamegraph ' tool is to receive a stack trace file of your system, parse it, and generate an SVG visualization. In order to get one of the mysterious stack trace files, we can use the [pprof] (HTTPS://GITHUB.COM/GOOGLE/PPROF) tool installed with go. In order to integrate things together, free from the pain of installing and configuring more software, we will use the excellent library of [Uber/go-torch] (Https://github.com/uber/go-torch)-it provides a very convenient container-style workflow for the entire process. Flamegraph can be generated from a variety of configuration files, each targeting different performance metrics. You can use the same toolkit and methodology to find CPU performance bottlenecks, memory leaks, and even deadlock processes. Here's a "flamegraph" for our sample app, execute the following command to grab the ' Uber/go-torch ' container and point it to your app. "' # Run for SECONDSDOCker run uber/go-torch-u http://

Via:http://brendanjryan.com/golang/profiling/2018/02/28/profiling-go-applications.html

Author: Brendanj Ryan Translator: Krystollia proofreading: Rxcai

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

109 Reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.