<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Perf | Easton Man's Blog</title>
	<atom:link href="https://blog.eastonman.com/blog/tag/perf/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.eastonman.com</link>
	<description>临渊羡鱼，不如退而结网</description>
	<lastBuildDate>Mon, 15 Feb 2021 11:10:25 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.6</generator>

<image>
	<url>https://blog.eastonman.com/wp-content/uploads/2021/02/cropped-Logo-e1613298891313-32x32.png</url>
	<title>Perf | Easton Man's Blog</title>
	<link>https://blog.eastonman.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>使用Perf进行程序热点分析</title>
		<link>https://blog.eastonman.com/blog/2021/02/use-perf/</link>
					<comments>https://blog.eastonman.com/blog/2021/02/use-perf/#respond</comments>
		
		<dc:creator><![CDATA[Easton Man]]></dc:creator>
		<pubDate>Sun, 14 Feb 2021 12:03:33 +0000</pubDate>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[Perf]]></category>
		<category><![CDATA[Profiling]]></category>
		<guid isPermaLink="false">https://blog.eastonman.com/?p=428</guid>

					<description><![CDATA[<p>预计阅读时间： 5 分钟Perf是一个性能分析工具，自从Linux 2.6.31（2009年）以来就被加入了内 [&#8230;]</p>
The post <a href="https://blog.eastonman.com/blog/2021/02/use-perf/">使用Perf进行程序热点分析</a> first appeared on <a href="https://blog.eastonman.com">Easton Man's Blog</a>.]]></description>
										<content:encoded><![CDATA[<p class="wpwc-reading-time">预计阅读时间： 5 分钟</p>
<p>Perf是一个性能分析工具，自从Linux 2.6.31（2009年）以来就被加入了内核。它利用内核运行时插桩的方式检测程序的运行，可以提供相当丰富的信息，足以让我们找到程序运行中的性能瓶颈和优化重点。</p>



<amp-fit-text layout="fixed-height" min-font-size="6" max-font-size="72" height="80"><h2 class="wp-block-heading">安装</h2></amp-fit-text>



<p>在某些系统中可能有预装完整的Perf，但是在我所使用的Debian Buster（10）上，只有用户空间的程序被预装了，所以还需安装对应的内核工具。通常来说，以下的这一条命令可以安装对应内核版本的Perf内核部分。但是如果此时正在使用的内核不是apt中最新的内核，则需要重启以切换到新的内核，或者安装指定版本的Perf内核工具。</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-28f84493 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-vertically-aligned-bottom is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:100%">
<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">sudo apt install linux-perf
sudo apt install linux-perf-5.8 # 指定内核版本</pre>
</div></div>
</div>
</div>



<p>此时我们应该已经可以运行perf了，但是通常会出现以下的结果：</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$> perf record
Error:
You may not have permission to collect stats.
Consider tweaking /proc/sys/kernel/perf_event_paranoid:
 -1 - Not paranoid at all
  0 - Disallow raw tracepoint access for unpriv
  1 - Disallow cpu events for unpriv
  2 - Disallow kernel profiling for unpriv</pre>



<p>或者说这样</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Error:
Access to performance monitoring and observability operations is limited.
Consider adjusting /proc/sys/kernel/perf_event_paranoid setting to open
access to performance monitoring and observability operations for processes
without CAP_PERFMON, CAP_SYS_PTRACE or CAP_SYS_ADMIN Linux capability.
More information can be found at 'Perf events and tool security' document:
https://www.kernel.org/doc/html/latest/admin-guide/perf-security.html
perf_event_paranoid setting is 3:
  -1: Allow use of (almost) all events by all users
      Ignore mlock limit after perf_event_mlock_kb without CAP_IPC_LOCK
>= 0: Disallow raw and ftrace function tracepoint access
>= 1: Disallow CPU event access
>= 2: Disallow kernel profiling
To make the adjusted perf_event_paranoid setting permanent preserve it
in /etc/sysctl.conf (e.g. kernel.perf_event_paranoid = &lt;setting>)</pre>



<p>这是因为出于安全考虑，内核在默认情况下禁止非特权用户监测系统性能。解决的办法有以下几种：</p>



<ul class="wp-block-list"><li>修改<code>kernel.perf_event_paranoid</code>内核参数</li><li>给perf加入CAP_PERFMON权限位</li><li>使用root用户进行性能监测</li></ul>



<p>我自己一般使用第一种，因此介绍第一种方法的详细做法。不推荐使用root用户运行perf，因为这样可能会有安全隐患。</p>



<p>修改<code>kernel.perf_event_paranoid</code>参数有两种做法。第一种方法是临时的，重启后就失效了，但是快速一点</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">sudo sh -c "echo -1 > /proc/sys/kernel/perf_event_paranoid"</pre>



<p>或者使用<code>sysctl</code>命令</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">sudo sysctl -w kernel.perf_event_paranoid=-1</pre>



<p>第二种方法是修改<code>sysctl</code>的配置文件，在我的环境中，这个文件位于<code>/etc/sysctl.conf</code>，有的系统中会使用<code>/etc/sysctl.d</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">sudo sh -c 'echo "kernel.perf_event_paranoid=-1" >> /etc/sysctl.conf'
sudo sysctl -p</pre>



<p>这样操作完成以后，内核就会允许非特权用户使用perf内核部分中的接口了。</p>



<h2 class="wp-block-heading">使用</h2>



<p>perf有几种常用的使用方式，第一种是较为简单的粗略了解程序使用硬件的情况</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$> perf stat ls

&lt;stdout>

Performance counter stats for 'ls':

              1.87 msec task-clock                #    0.411 CPUs utilized
                11      context-switches          #    0.006 M/sec
                 0      cpu-migrations            #    0.000 K/sec
                94      page-faults               #    0.050 M/sec
         2,771,746      cycles                    #    1.479 GHz
         1,534,926      instructions              #    0.55  insn per cycle
           317,631      branches                  #  169.519 M/sec
            15,169      branch-misses             #    4.78% of all branches

       0.004553499 seconds time elapsed

       0.003498000 seconds user
       0.000000000 seconds sys</pre>



<p>第二种也是功能强大的一种，可以详细分析程序各函数的运行时间占比，还可以查看这些函数中各个指令的耗时占比，这使得我们可以精确地了解程序运行时的瓶颈的处理器资源使用情况。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">perf record &lt;program>
perf report</pre>



<p>这时我们就可以看到类似这样的界面</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="223" src="https://blog.eastonman.com/wp-content/uploads/2021/02/Screenshot-2020-10-22-185947-1024x223.png" alt="" class="wp-image-442" srcset="https://blog.eastonman.com/wp-content/uploads/2021/02/Screenshot-2020-10-22-185947-1024x223.png 1024w, https://blog.eastonman.com/wp-content/uploads/2021/02/Screenshot-2020-10-22-185947-300x65.png 300w, https://blog.eastonman.com/wp-content/uploads/2021/02/Screenshot-2020-10-22-185947-768x167.png 768w, https://blog.eastonman.com/wp-content/uploads/2021/02/Screenshot-2020-10-22-185947.png 1231w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>此时按下A可以看到反汇编后的汇编代码和相应的时间占比。</p>



<p>有的时候如果编译时关闭了debug选项（如gcc -g）那么perf很可能不能得到正确的调用栈，这样时间占比的统计就会有问题，不利于我们观察热点函数，此时可以指定perf使用更详细的调用栈跟踪方法，例如使用lbr</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">perf record --call-graph lbr &lt;program></pre>



<p>perf可以使用的调用栈跟踪方法有三种：</p>



<ul class="wp-block-list"><li>fp：最不详细，产生的记录文件也最小，对程序的性能几乎无影响。</li><li>lbr：较为详细，产生的记录文件显著增大，对程序的性能有少量的影响。</li><li>dwarf：最详细，产生的记录文件极其巨大，1分钟可能能记录10G，对程序性能有显著影响，因此并不很实用。</li></ul>



<p>对我来说一般直接选择lbr就可以了，如果硬盘不够大或者读写几个G的文件很慢的话再考虑fp。</p>



<p>这几种调用栈跟踪方式的详细区别可以参考<a href="https://zh-blog.logan.tw/2019/10/06/intro-to-perf-events-and-call-graph/" target="_blank" rel="noreferrer noopener" title="https://zh-blog.logan.tw/2019/10/06/intro-to-perf-events-and-call-graph/">大神博客</a></p>



<h2 class="wp-block-heading">深入阅读</h2>



<ul class="wp-block-list"><li><a href="https://www.singlestore.com/blog/linux-off-cpu-investigation/" target="_blank" rel="noreferrer noopener" title="https://www.singlestore.com/blog/linux-off-cpu-investigation/">Investigating Linux Performance with Off-CPU Flame Graphs</a></li><li><a href="http://www.brendangregg.com/blog/2016-01-20/ebpf-offcpu-flame-graph.html" target="_blank" rel="noreferrer noopener" title="http://www.brendangregg.com/blog/2016-01-20/ebpf-offcpu-flame-graph.html">Linux eBPF Off-CPU Flame Graph</a></li><li><a href="https://github.com/brendangregg/FlameGraph" target="_blank" rel="noreferrer noopener" title="https://github.com/brendangregg/FlameGraph">FlameGraph</a></li></ul>



<p></p>The post <a href="https://blog.eastonman.com/blog/2021/02/use-perf/">使用Perf进行程序热点分析</a> first appeared on <a href="https://blog.eastonman.com">Easton Man's Blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.eastonman.com/blog/2021/02/use-perf/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
