您的位置 首页 golang

大话golang性能分析(一):profile基本原理

O 专题目标

  • 理解profile基本原理
  • 熟悉go常用性能分析工具pprof
  • 快速对线上服务的cpu、内存、goroutine的问题进行分析和排查

对性能分析,golang是采取采样分析的方式,语言原生支持对运行的程序进行采样,收集采样数据通过累加计算并通过提供相应的工具来分析堆栈信息。【对比 java :java通过发布jdk周边工具jps jmap j Stack 等,在问题分析前先将内存中的数据进行dump的方式进行分析】

一 profile原理

A Profile is a collection of stack traces showing the call sequences that led to instances of a particular event, such as allocation. Packages can create and maintain their own profiles; the most common use is for tracking resources that must be explicitly closed, such as files or network connections.

go默认会初始化六种profile, 每种profile存储的实际内容被抽象为 ​countProfile​,存储栈帧地址,堆栈地址通过调用​ runtime .CallersFrames(stk)​可以获取堆栈信息,下面主要讲最常用的三种方式:内存、CPU和协程

type countProfile interface { 
 Len() int
 Stack(i int) []uintptr
}
// A countProfile is a set of  stack  traces to be printed as counts grouped by stack trace. There are multiple implementations:all that matters is that we can find out how many traces there are and obtain each trace in turn.
 
  • 内存采样

go程序启动后,runtime会按照一定频率对内存的分配进行采样记录,当内存分配每达到一定值(默认是512KB,参数由​runtime.MemProfileRate​设定), runtime就会记录下当前这次内存分配的大小、stack等信息到profile

type MemProfileRecord struct {
 AllocBytes, FreeBytes int64 // number of bytes allocated, freed
 AllocObjects, FreeObjects int64 // number of objects allocated, freed
 Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry
}
 
  • CPU采样

cpu的采样是通过调用函数​StartCPUProfile​来启动采样的,结束调用​StopCPUProfile​调用链如下StartCPUProfile​->​runtime.SetCPUProfileRate​->​sighandler​;采样频率是100hz

// The runtime routines allow a variable profiling rate,
// but in practice operating systems cannot trigger signals
// at more than about 500 Hz, and our processing of the
// signal is not cheap (mostly getting the stack trace).
// 100 Hz is a reasonable choice: it is frequent enough to
// produce useful data, rare enough not to bog down the
// system, and a nice round number to make it easy to
// convert sample counts to seconds. Instead of requiring
// each client to specify the frequency, we hard code it.
const hz = 100
// readProfile, provided by the runtime, returns the next chunk of
// binary CPU profiling stack trace data, blocking until data is available.
// If profiling is turned off and all the profile data accumulated while it was
// on has been returned, readProfile returns eof=true.
// The caller must save the returned data and tags before calling readProfile again.
func readProfile() (data []uint64, tags []unsafe.Pointer, eof bool)
 
  • goroutine采样

GMP模型中,G goroutine P context M thread,采样数据来源于P,运行中的协程上下文堆栈。P会维护当前执行队列,队列中是M对应的G队列。自行检索GPM原理(关键字:窃取、61分之一全局队列)

如何将采样内容汇总?

假设我们在程序执行的某个时刻取样得到一个栈帧序列是ABC,可以得到的信息包括:此刻运行的函数是C,是从函数B调用到C的。当取样很多次后进行统计,就可以得到调用的信息。比如对下面这段代码的取样:

  • void A() { B(); for (int i=0; i<3; i++) C(); } void B() { for (int i=0; i<5; i++) C(); }
  • 将得到
  • A AB ABC ABC ABC AC 根据统计信息: 函数累加耗时和调用关系,根据这些数据可以构造有向图
大话golang性能分析(一):profile基本原理

profiles采样后会以pprof-formatted格式存储起来,分析这些数据需要用到golang的分析工具。

下一节分享golang常用的分析工具,敬请期待。欢迎关注”大龄码农”,一起来探讨技术背后的原理!

文章来源:智云一二三科技

文章标题:大话golang性能分析(一):profile基本原理

文章地址:https://www.zhihuclub.com/98935.shtml

关于作者: 智云科技

热门文章

评论已关闭

29条评论

  1. Hydroxychloroquine sulfate tablets, USP for oral administration contain 200 mg hydroxychloroquine sulfate, USP equivalent to 155 mg base and the following inactive ingredients anhydrous lactose, croscarmellose sodium, glyceryl triacetate, hypromellose, magnesium stearate, microcrystalline cellulose, polydextrose, polyethylene glycol, povidone, sodium lauryl sulfate and titanium dioxide

  2. 2 of all live born infants resulting from treatment were achieved via IVF Researchers tested 13 drugs that restrict the enzymes and found all of them more effective than the current treatment for primary amebic meningoencephalitis recommended by the Centers for Disease Control and Prevention, miltefosine

  3. The preliminary results of an Eastern Cooperative Oncology Group ECOG trial of cyclophosphamide, doxorubicin, and 5 fluorouracil CAF alone vs the addition of goserelin vs the addition of both goserelin and tamoxifen in premenopausal women with hormone receptor positive breast cancer suggested benefit for goserelin and tamoxifen most clearly in patients under 40 with high baseline estradiol levels

  4. Some mutations may be beneficial, whereas others may have no obvious effect Background Most women with oestrogen receptor ER positive primary breast cancer receive adjuvant tamoxifen after surgery

  5. These pollutants can cause health problems for those conducting the open burn as well as anyone nearby

  6. compazine ivermectin kvapky cena Veghte takes over immediately as head of the division, and will not be replaced as HP s chief operating officer

  7. 7 of participants receiving Tamoxifen Remedica tamoxifen citrate and placebo therapy, respectively withdrew from the trial for medical reasons

  8. com 20 E2 AD 90 20Se 20Puede 20Comprar 20Viagra 20Sin 20Receta 20En 20Farmacias 20Fsicas 202020 20 20Female 20Viagra 20Olx se puede comprar viagra sin receta en farmacias fsicas 2020 In addition to concerns raised about how the EU would respond to the execution, Missouri s decision to use propofol prompted a lawsuit filed on behalf of nearly two dozen death row inmates claiming use of the unproven execution drug could result in pain and suffering for the condemned man Br J Haematol 2006; 133 206 209

  9. com 20 E2 AD 90 20Viagra 20Femenino 20Nombre 20Comercial 20 20Viagra 20Kalp 20Krizine 20Neden 20Olurmu viagra kalp krizine neden olurmu At the makeshift morgue at the sit in, supporters chanted The people want to execute the butcher, referring to army chief and Defense Minster Gen

  10. norethindrone pristiq vs cymbalta for fibromyalgia A backbencher called on Mr Miliband to carry out an aggressive reshuffle of his shadow cabinet because some people in it were just treading water and should be replaced by some young MPs who can carry a message and are hungry to make an impact Eight months after surgical excision of verrucous skin lesions

  11. This will help ensure that your body has time to absorb the NPP and give you the best possible results

  12. Calderillo Ruiz, Hospital Medica Sur, Mexico; O s management of the fund, Davian referred to his illnessГ‚ as resulting from an Гў

  13. The lipid extracts of cells and media were analyzed by TLC using chloroform methanol 15 mM calcium chloride 60 35 8, by volume as the developing solvent Merrill rOaSaHJXpOQsiYt 6 19 2022

  14. Also I think they call it Halodrol MT now which is probley the same formula as the Halodrol Liquid Gels the name that replaced the Halodrol 50 I am new to this; a 3 yr

  15. Bukod, habang nakikilala namin ang kahalagahan ng puna ng mga customer, ang produkto ay patuloy na napabuti upang matugunan ang mga na update na kinakailangan

  16. 58, 59 Leptin replacement therapy, administered as subcutaneous recombinant methionyl human leptin r- metHuLeptin twice daily for 2 3 months in women with FHA was found to increase markers of bone- formation, suggesting that leptin plays a role in bone density Analysis of the causal connection between Tregs and CD8 T cells required the use of skin grafts on Foxp3 DTR mice, so it remains uncertain whether Tregs are the predominant tumor escape mechanism during autochthonous tumorigenesis

  17. 4 6 weeks old white leghorn chickens were divided into groups n 4 that were housed separately, and which were provided clean water daily and control untreated diet consisting of a cracked corn mix Chick Start and Grow, Northern Colorado Feeders Supply mixed with any additives that were also added to IVM treated diet for 3 or 7 consecutive days

  18. Gynecomastia is predominantly a result of hormonal changes in the body that lead to an imbalance between testosterone and estrogen, though recent research has suggested that the condition may also be genetic which explains why it seems to develop at any age regardless of hormones Pharmaceutical companies say that they charge high prices for medications because they need that revenue to invest in research and development R D

  19. Use of an alpha lipoic, methylsulfonylmethane and bromelain dietary supplement Opera for chemotherapy induced peripheral neuropathy management, a prospective study

  20. trachomatis causes PELVIC INFLAMMATORY DISEASE PID and has long term consequences such as infertility, ECTOPIC PREGNANCY and chronic pelvic pain that are secondary to scarring of the fallopian tubes caused by SALPINGITIS and ovaries

网站地图