当前位置:网站首页>Inventory development artifact in golang
Inventory development artifact in golang
2021-09-15 04:28:22 【roshilikang】
This article has been included https://github.com/lkxiaolou/lkxiaolou welcome star.
stay Java in , We use it Junit Unit test , use JMH Performance benchmark (benchmark), use async-profiler analyse cpu performance , use jstack、jmap、arthas Wait to find out the problem . As a relatively new programming language ,golang Are these tools easier to use ?
unit testing
Java Unit testing requires the use of third-party libraries , It's usually Junit, It's complicated to configure . In the use of the golang And then I found out golang The unit test that comes with it is really simple . If we have one cal.go file , Then the corresponding unit test file is cal_test.go, The method must be named TestXxx, This method of unit testing by name is simple and effective , That's what we usually say “ Convention over configuration ”. Let's take a simple example :
package unit
func add(a int, b int) int {
return a + b
}
func sub(a int, b int) int {
return a - b
}
package unit
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestAdd(t *testing.T) {
assert.Equal(t, 10, add(5, 5))
}
func TestSub(t *testing.T) {
assert.Equal(t, 0, sub(5, 5))
}
Unit tests only need to be run ( More usage references go help test)
go test --cover cal_test.go cal.go -v

benchmark
It's similar to unit testing ,golang Of benchmark It's also out of the box . stay cal_test.go Add one more BenchmarkAdd Method
package unit
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestAdd(t *testing.T) {
assert.Equal(t, 10, add(5, 5))
}
func TestSub(t *testing.T) {
assert.Equal(t, 0, sub(5, 5))
}
func BenchmarkAdd(b *testing.B) {
for i:= 0; i < b.N; i++ {
add(5, 5)
}
}
Execution can be ( More usage references go help test)
go test -bench=. -cpu=4 -count=3

pprof
pprof yes golang It can be used to make cpu、 Memory 、 Tools for lock analysis , Very similar java Of async-profiler. pprof Is very simple to use , You just need to bring in the code net/http/pprof package , Then listen to a port . A simple example is as follows :
package main
import (
"fmt"
"log"
"net/http"
"time"
_ "net/http/pprof"
)
func main() {
go func() {
//example: visit http://127.0.0.1:6060/debug/pprof in browser.
err := http.ListenAndServe("0.0.0.0:6060", nil)
if err != nil {
fmt.Println("failed to start pprof goroutine:", err)
}
}()
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
time.Sleep(1 * time.Second)
eat()
time := time.Now().Unix() * 2 + 1000000
fmt.Fprintf(w, "URL.Path = %q; time = %d\n", r.URL.Path, time)
}
func eat() {
loop := 10000000000
for i := 0; i < loop; i++ {
// do nothing
}
}
Enter... On the command line
go tool pprof http://127.0.0.1:6060/debug/pprof/profile
At the same time , Give Way pprof It can collect data , My request here is
curl http://127.0.0.1:8000/hello
wait for 30 Seconds later , At the end of the acquisition, the address of the acquisition file will be displayed
Saved profile in /Users/roshi/pprof/pprof.samples.cpu.003.pb.gz
You can use top Wait for the command to view directly cpu Functions that consume too much , More commands can be used help see .

Or download the file and analyze it with visual interface , have access to
go tool pprof -http=":8080" /User/roshi/pprof/pprof.samples.cpu.003.pb.gz
To open a visual page , see , If an error is reported, it needs to be installed graphviz, The installation documentation can be found here :https://graphviz.gitlab.io/download/
visit http://localhost:8080/ui/
You can see the following , The block with the largest area represents consumption cpu most

Here's an article right pprof The presentation was very detailed , You can refer to :https://blog.wolfogre.com/posts/go-ppof-practice/
dlv
pprof useful , But one drawback is that it must be opened in the code in advance , If there is a problem online and it is not turned on pprof, You might need something like that jstack、jmap、arthas And so on . Here is a very good one that has been used recently golang A sharp tool for troubleshooting ——dlv, Please refer to
https://github.com/go-delve/delve
One of its useful features is attach, Sure attach To the running golang Program , see goroutine. This is a good way to check online problems . The installation of each platform is in github It's very clear , What needs to be explained is the installation dlv Of golang Version and process to be checked golang The version needs to be consistent . Write a test program first , Two goroutine, A running , A block
package main
import (
"fmt"
"sync"
)
func main() {
go count()
go wait()
wait()
}
func count() {
count := 0
for {
count = count + 1
if count % 1000000000 == 0 {
fmt.Println("I'm a running routine")
}
}
}
func wait() {
wg := sync.WaitGroup{}
wg.Add(1)
wg.Wait()
}
Run up , And then use dlv Conduct attach, Here's the picture ( The specific order is OK attach After use help see )

So it's very convenient to see all of them goroutine What are you doing
At the end
As a relatively new programming language ,golang The essence of existing languages is its essence. , Bring necessary tools with you , Lower the threshold further , It's very friendly for beginners to learn .
About author : Focus on back-end middleware development , official account " Master bug catcher " author , Pay attention to me , Give you the purest technical dry goods

版权声明
本文为[roshilikang]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/09/20210909112309746e.html
边栏推荐
- Garde la distance.
- 90 lines of code to implement the module packer
- When the OrCAD schematic is opened, suddenly the schematic file cannot be found
- Purpose and difference between Maitreya clamp and active clamp of IGBT
- [PHP source code] z-blogphp pirate navigation theme template
- Architecture and data science behind hundreds of thousands of experiments a year
- 大廠Android面試總結 詳細解答,Android技術圖譜
- Résumé de l'entrevue Android de Dachang, carte technique Android
- 大厂程序员35岁后的职业出路在哪,京东最新Android面试真题解析
- 万字长文,面试官老爱问适配器模式与外观模式,
猜你喜欢
-
大厂Offer拿到手软啊,程序员中年危机
-
大厂Offer拿到手软啊,不可思议
-
Le résumé de l'entrevue Android de Dachang est en retard
-
Agent de cache SQUID
-
6 - year New Bird Development interview Byte Jumping Android R & D Post, Dry goods collation
-
Notes d'étude de HongMeng, 714 pages PDF, or, neuf, argent et dix
-
大廠Offer拿到手軟啊,不可思議
-
L'offre de la grande usine est douce. Incroyable.
-
L'offre d'une grande usine est douce.
-
L'intervieweur demande toujours le mode adaptateur et le mode d'apparence.
随机推荐
- Où est la sortie professionnelle pour les programmeurs d'usine après 35 ans?
- 大廠Offer拿到手軟啊,程序員中年危機
- Stockage de produits Cloud packages, illimité et gratuit
- Opencv4 machine learning (VI): principle and implementation of k-means
- [yolop interpretation] you only look once for panoramic driving perception
- Tencent Cloud et d'autres systèmes de protection préférentiels
- Nombre maximum de points en ligne droite
- [interpretation of pointpillars] fast encoder for point cloud target detection
- [rangenet + + interpretation] fast and accurate lidar semantic segmentation
- [yolof interpretation] you only look one level feature (CVPR 2021)
- [SNE roadseg interpretation] pavement segmentation network combined with surface normal vector (eccv2020)
- [yolox interpretation] anchor free target detector comparable to yolov5!
- Opencv4 machine learning (4): geometric transformation and affine transformation of images
- Detailed explanation of fast SCNN semantic segmentation network
- 萬字長文,面試官老愛問適配器模式與外觀模式,
- 大牛耗时一年最佳总结,让你的app体验更丝滑,BAT大厂面试总结
- 不敢跟面试官对线,通过五轮面试斩获offer阿里实习生亲述,
- Comparison of location loss functions in target detection network: IOU, giou, ciou, Diou, L1, L2, smooth L1
- Blue Bridge Cup software provincial competition in April 2021: title + analysis (full version)
- [C + + cultivation plan] don't talk about learning, just talk about dry goods (Day1)
- Tf2.0 deep learning practice (1): handwritten numeral recognition for classification problem
- 大廠程序員35歲後的職業出路在哪,京東最新Android面試真題解析
- Invitation | réunion Apache Pulsar 2021 - Shenzhen ce samedi
- The Dot Net Application Domain Study
- Trigger study
- Universal code, achieving with action -- Safety code scanning Professional Committee
- N'osez pas vous opposer à l'intervieweur et obtenir des commentaires personnels des stagiaires d'offer Ali après cinq rondes d'entrevue.
- Daniel prend le meilleur résumé de l'année pour rendre votre expérience d'application plus soyeuse.
- Easy to use and convenient development team management tool -- apipost
- 如何试出一个Android开发者真正的水平,【面试总结】
- 如何才能通过一线互联网公司面试,Android经典入门教程
- Comment passer une entrevue avec une entreprise Internet de première ligne, Android Classic Getting started tutoriel
- Comment essayer un développeur Android vraiment niveau, 【 résumé de l'entrevue 】
- Ad redefines PCB size
- [wonderful learning journey of cloud computing] phase I: getting to know cloud computing for the first time
- Sf58-asemi high voltage fast recovery diode in-line package
- Asp.net quick build application page main framework
- Soul painter: cartoon illustration SSH
- Special live broadcast of the first anniversary celebration of Hongmeng community · invitation letter
- Mathematics Interview Questions (X)