blog

Personal blog
git clone git://git.laack.co/blog.git
Log | Files | Refs

basic-software-profiling-cpu-usage.html (36486B)


      1 <!DOCTYPE html>
      2 <html xmlns="http://www.w3.org/1999/xhtml">
      3 <head>
      4   <meta charset="utf-8" />
      5   <meta name="generator" content="pandoc 3.10.2" />
      6   <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
      7   <title>basic-software-profiling-cpu-usage</title>
      8   <style>
      9     /* Default styles provided by pandoc.
     10     ** See https://pandoc.org/MANUAL.html#variables-for-html for config info.
     11     */
     12     span.smallcaps{font-variant: small-caps;}
     13     div.columns{display: flex; gap: 1.5em;}
     14     div.column{flex: auto;}
     15     @media screen {
     16     div.columns{gap: min(4vw, 1.5em);}
     17     div.column{overflow-x: auto;}
     18     }
     19     div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
     20     /* The extra [class] is a hack that increases specificity enough to
     21        override a similar rule in reveal.js */
     22     ul.task-list[class]{list-style: none;}
     23     ul.task-list li input[type="checkbox"] {
     24       font-size: inherit;
     25       width: 0.8em;
     26       margin: 0 0.8em 0.2em -1.6em;
     27       vertical-align: middle;
     28     }
     29     .display.math{display: block; text-align: center; margin: 0.5rem auto;}
     30     /* CSS for syntax highlighting */
     31     html { -webkit-text-size-adjust: 100%; }
     32     pre > code.sourceCode { white-space: pre; position: relative; }
     33     pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
     34     pre > code.sourceCode > span:empty { height: 1.2em; }
     35     .sourceCode { overflow: visible; }
     36     code.sourceCode > span { color: inherit; text-decoration: inherit; }
     37     div.sourceCode { margin: 1em 0; }
     38     pre.sourceCode { margin: 0; }
     39     @media screen {
     40     div.sourceCode { overflow: auto; }
     41     }
     42     @media print {
     43     pre > code.sourceCode { white-space: pre-wrap; }
     44     pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
     45     }
     46     pre.numberSource code
     47       { counter-reset: source-line 0; }
     48     pre.numberSource code > span
     49       { position: relative; left: -4em; counter-increment: source-line; }
     50     pre.numberSource code > span > a:first-child::before
     51       { content: counter(source-line);
     52         position: relative; left: -1em; text-align: right; vertical-align: baseline;
     53         border: none; display: inline-block;
     54         -webkit-touch-callout: none; -webkit-user-select: none;
     55         -khtml-user-select: none; -moz-user-select: none;
     56         -ms-user-select: none; user-select: none;
     57         padding: 0 4px; width: 4em;
     58         background-color: #ffffff;
     59         color: #a0a0a0;
     60       }
     61     pre.numberSource { margin-left: 3em; border-left: 1px solid #a0a0a0;  padding-left: 4px; }
     62     div.sourceCode
     63       { color: #1f1c1b; background-color: #ffffff; }
     64     @media screen {
     65     pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
     66     }
     67     code span { color: #1f1c1b; } /* Normal */
     68     code span.al { color: #bf0303; background-color: #f7e6e6; font-weight: bold; } /* Alert */
     69     code span.an { color: #ca60ca; } /* Annotation */
     70     code span.at { color: #0057ae; } /* Attribute */
     71     code span.bn { color: #b08000; } /* BaseN */
     72     code span.bu { color: #644a9b; font-weight: bold; } /* BuiltIn */
     73     code span.cf { color: #1f1c1b; font-weight: bold; } /* ControlFlow */
     74     code span.ch { color: #924c9d; } /* Char */
     75     code span.cn { color: #aa5500; } /* Constant */
     76     code span.co { color: #898887; } /* Comment */
     77     code span.cv { color: #0095ff; } /* CommentVar */
     78     code span.do { color: #607880; } /* Documentation */
     79     code span.dt { color: #0057ae; } /* DataType */
     80     code span.dv { color: #b08000; } /* DecVal */
     81     code span.er { color: #bf0303; text-decoration: underline; } /* Error */
     82     code span.ex { color: #0095ff; font-weight: bold; } /* Extension */
     83     code span.fl { color: #b08000; } /* Float */
     84     code span.fu { color: #644a9b; } /* Function */
     85     code span.im { color: #ff5500; } /* Import */
     86     code span.in { color: #b08000; } /* Information */
     87     code span.kw { color: #1f1c1b; font-weight: bold; } /* Keyword */
     88     code span.op { color: #1f1c1b; } /* Operator */
     89     code span.ot { color: #006e28; } /* Other */
     90     code span.pp { color: #006e28; } /* Preprocessor */
     91     code span.re { color: #0057ae; background-color: #e0e9f8; } /* RegionMarker */
     92     code span.sc { color: #3daee9; } /* SpecialChar */
     93     code span.ss { color: #ff5500; } /* SpecialString */
     94     code span.st { color: #bf0303; } /* String */
     95     code span.va { color: #0057ae; } /* Variable */
     96     code span.vs { color: #bf0303; } /* VerbatimString */
     97     code span.wa { color: #bf0303; } /* Warning */
     98   </style>
     99   <link rel="stylesheet" href="style.css" />
    100 </head>
    101 <body>
    102 <h1 id="basic-software-profiling-cpu-usage">Basic Software Profiling: CPU Usage</h1>
    103 <h2 id="date-20261017">Date: 2026/10/17</h2>
    104 <p>Software today is much slower than it should be. I believe this is, in part, because most software developers do not understand performance.</p>
    105 <p>An easily explainable aspect of performance is profiling, and in this post I’ll discuss the basics of if. I’ll be focusing on compiled programs, but the core ideas may be applied to interpreted programs too.</p>
    106 <h2 id="tools">Tools</h2>
    107 <p><a href="https://en.wikipedia.org/wiki/Perf_%28Linux%29">Perf</a> is a suite of tools for program profiling on Linux. We will mainly use it to collect aggregate performance metrics and call stack information. Analogous tools exist for other Free operating systems, and many bespoke tools exist for interpreted programs.</p>
    108 <p><a href="https://github.com/brendangregg/FlameGraph">Flamegraph</a> is a suite of tools for generating flamegraphs, a type of graph designed for the visualization of performance data. I’ll be using my <a href="https://git.laack.co/flamegraph">fork of flamegraph</a> which doesn’t add j***s***** to generated SVGs, but apart from that they function identically.</p>
    109 <h2 id="reading-a-flamegraph">Reading a Flamegraph</h2>
    110 <p>Look at the flamegraph and try to understand the performance characteristics of the program:</p>
    111 <object data="/images/ex1-fg.svg" type="image/svg+xml" width="100%">
    112 </object>
    113 <details>
    114 <summary>
    115 Source code for the program that generated this flamegraph
    116 </summary>
    117 <div class="sourceCode" id="cb1"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="dt">uint32_t</span> square<span class="op">(</span><span class="dt">uint32_t</span> input<span class="op">)</span> <span class="op">{</span></span>
    118 <span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>    <span class="cf">return</span> input <span class="op">*</span> input<span class="op">;</span></span>
    119 <span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
    120 <span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a></span>
    121 <span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="co">// helper function to show stack depths</span></span>
    122 <span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="dt">uint32_t</span> squareHelper<span class="op">(</span><span class="dt">uint32_t</span> input<span class="op">)</span> <span class="op">{</span></span>
    123 <span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a>    <span class="dt">uint32_t</span> x <span class="op">=</span> <span class="dv">100</span> <span class="op">*</span> <span class="dv">100</span><span class="op">;</span></span>
    124 <span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>    <span class="cf">return</span> square<span class="op">(</span>input<span class="op">);</span></span>
    125 <span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
    126 <span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a></span>
    127 <span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a><span class="dt">uint32_t</span> factorial<span class="op">(</span><span class="dt">uint32_t</span> input<span class="op">)</span> <span class="op">{</span></span>
    128 <span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a>    <span class="dt">uint32_t</span> acc <span class="op">=</span> <span class="dv">1</span><span class="op">;</span></span>
    129 <span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a></span>
    130 <span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a>    <span class="cf">while</span><span class="op">(</span>input <span class="op">&gt;</span> <span class="dv">1</span><span class="op">)</span> <span class="op">{</span></span>
    131 <span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a>        acc <span class="op">*=</span> input<span class="op">;</span></span>
    132 <span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a>        input <span class="op">-=</span> <span class="dv">1</span><span class="op">;</span></span>
    133 <span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
    134 <span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a>    <span class="cf">return</span> acc<span class="op">;</span></span>
    135 <span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
    136 <span id="cb1-20"><a href="#cb1-20" aria-hidden="true" tabindex="-1"></a></span>
    137 <span id="cb1-21"><a href="#cb1-21" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> main<span class="op">()</span> <span class="op">{</span></span>
    138 <span id="cb1-22"><a href="#cb1-22" aria-hidden="true" tabindex="-1"></a></span>
    139 <span id="cb1-23"><a href="#cb1-23" aria-hidden="true" tabindex="-1"></a>    <span class="dt">uint32_t</span> ub <span class="op">=</span> <span class="bu">std::</span>sqrt<span class="op">(</span>UINT32_MAX<span class="op">);</span></span>
    140 <span id="cb1-24"><a href="#cb1-24" aria-hidden="true" tabindex="-1"></a></span>
    141 <span id="cb1-25"><a href="#cb1-25" aria-hidden="true" tabindex="-1"></a>    <span class="cf">for</span><span class="op">(</span><span class="dt">uint32_t</span> i <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> i <span class="op">&lt;</span> ub<span class="op">;</span> <span class="op">++</span>i<span class="op">)</span> <span class="op">{</span></span>
    142 <span id="cb1-26"><a href="#cb1-26" aria-hidden="true" tabindex="-1"></a>        <span class="cf">for</span><span class="op">(</span><span class="dt">uint32_t</span> x <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> x <span class="op">&lt;</span> <span class="dv">100000</span><span class="op">;</span> <span class="op">++</span>x<span class="op">)</span> <span class="op">{</span></span>
    143 <span id="cb1-27"><a href="#cb1-27" aria-hidden="true" tabindex="-1"></a>            square<span class="op">(</span>i<span class="op">);</span></span>
    144 <span id="cb1-28"><a href="#cb1-28" aria-hidden="true" tabindex="-1"></a>        <span class="op">}</span></span>
    145 <span id="cb1-29"><a href="#cb1-29" aria-hidden="true" tabindex="-1"></a></span>
    146 <span id="cb1-30"><a href="#cb1-30" aria-hidden="true" tabindex="-1"></a>        <span class="cf">for</span><span class="op">(</span><span class="dt">uint32_t</span> x <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> x <span class="op">&lt;</span> <span class="dv">100000</span><span class="op">;</span> <span class="op">++</span>x<span class="op">)</span> <span class="op">{</span></span>
    147 <span id="cb1-31"><a href="#cb1-31" aria-hidden="true" tabindex="-1"></a>            squareHelper<span class="op">(</span>i<span class="op">);</span></span>
    148 <span id="cb1-32"><a href="#cb1-32" aria-hidden="true" tabindex="-1"></a>        <span class="op">}</span></span>
    149 <span id="cb1-33"><a href="#cb1-33" aria-hidden="true" tabindex="-1"></a></span>
    150 <span id="cb1-34"><a href="#cb1-34" aria-hidden="true" tabindex="-1"></a>        <span class="cf">for</span><span class="op">(</span><span class="dt">uint32_t</span> x <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> x <span class="op">&lt;</span> <span class="dv">20000</span><span class="op">;</span> <span class="op">++</span>x<span class="op">)</span> <span class="op">{</span></span>
    151 <span id="cb1-35"><a href="#cb1-35" aria-hidden="true" tabindex="-1"></a>            factorial<span class="op">(</span>x <span class="op">%</span> <span class="dv">10</span><span class="op">);</span></span>
    152 <span id="cb1-36"><a href="#cb1-36" aria-hidden="true" tabindex="-1"></a>        <span class="op">}</span></span>
    153 <span id="cb1-37"><a href="#cb1-37" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
    154 <span id="cb1-38"><a href="#cb1-38" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
    155 </details>
    156 <p>The amount of time spent with the <code>main</code> function on the call stack is represented by the width of its bar.</p>
    157 <p>Notice how there are multiple bars that say <code>square</code>. This is because we execute <code>square</code> at different call stack depths, and the width of each bar is proportional to the amount of time we spent with <code>square</code> on the call stack at a given stack depth.</p>
    158 <p>Given how the widths are calculated, we can deduce the top-down width of a bar is how much time the program spent executing a specific function. In the case of <code>squareHelper</code> and <code>square</code>, we see we spent more time executing <code>squareHelper</code> than <code>square</code>, evidenced by the fact that from a top-down view, <code>squareHelper</code> is wider.</p>
    159 <p>The astute among you might’ve noticed <code>square</code> and <code>squareHelper</code> seem to have been executed a few times outside of the main loop. This is due to how <code>perf</code> calculates the stack depth. The specifics of this are more in the weeds than we’ll discuss here, but it shouldn’t meaningfully impact the high level information that can be obtained from a flamegraph.</p>
    160 <h2 id="perf">Perf</h2>
    161 <p>I’ve been loose with my words in terms of the specific data being displayed by the flamegraph. The command I used to generate the data for the flamegraph doesn’t technically track the amount of time spent with a function on the stack at a given depth, we are instead tracking the number of on-CPU samples taken with the function on the top of the call stack. This distinction is important because things like blocking I/O will not be reflected in our timings.</p>
    162 <p>This is the command I ran to generate the data:</p>
    163 <div class="sourceCode" id="cb2"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="ex">perf</span> record <span class="at">-g</span> ./ex1</span></code></pre></div>
    164 <p>The <code>perf record</code> command is used to run a command and record its performance profile, which is written to the <code>perf.data</code> file. By default, <code>perf record</code> will sample at 1000Hz while the program is on-CPU. The final option, <code>-g</code>, is used to specify we are interested in having the call stack included in our data.</p>
    165 <p>To view aggregate information about the data in the <code>perf.data</code> file we can run:</p>
    166 <div class="sourceCode" id="cb3"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ex">perf</span> report <span class="at">-g</span></span>
    167 <span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a></span>
    168 <span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span>  100.00%     0.00%  ex1      ex1                   <span class="pp">[</span><span class="ss">.</span><span class="pp">]</span> _start</span>
    169 <span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span>  100.00%     0.00%  ex1      libc.so.6             <span class="pp">[</span><span class="ss">.</span><span class="pp">]</span> __libc_start_main</span>
    170 <span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span>  100.00%     0.00%  ex1      libc.so.6             <span class="pp">[</span><span class="ss">.</span><span class="pp">]</span> call_init <span class="er">(</span><span class="ex">inlined</span><span class="kw">)</span></span>
    171 <span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span>  100.00%     0.00%  ex1      libc.so.6             <span class="pp">[</span><span class="ss">.</span><span class="pp">]</span> 0x00007f6302a27781</span>
    172 <span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span>   99.79%    39.46%  ex1      ex1                   <span class="pp">[</span><span class="ss">.</span><span class="pp">]</span> main</span>
    173 <span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span>   34.97%    19.94%  ex1      ex1                   <span class="pp">[</span><span class="ss">.</span><span class="pp">]</span> squareHelper<span class="er">(</span><span class="ex">unsigned</span> int<span class="kw">)</span></span>
    174 <span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span>   29.99%    19.90%  ex1      ex1                   <span class="pp">[</span><span class="ss">.</span><span class="pp">]</span> square<span class="er">(</span><span class="ex">unsigned</span> int<span class="kw">)</span></span>
    175 <span id="cb3-10"><a href="#cb3-10" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span>   21.61%    20.69%  ex1      ex1                   <span class="pp">[</span><span class="ss">.</span><span class="pp">]</span> factorial<span class="er">(</span><span class="ex">unsigned</span> int<span class="kw">)</span></span>
    176 <span id="cb3-11"><a href="#cb3-11" aria-hidden="true" tabindex="-1"></a><span class="ex">...</span></span></code></pre></div>
    177 <p>If you are interested in information about which functions are calling each other, and the associated on-CPU times, you can run this command:</p>
    178 <div class="sourceCode" id="cb4"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ex">perf</span> report <span class="at">-g</span> <span class="at">--stdio</span></span>
    179 <span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a></span>
    180 <span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a><span class="ex">...</span></span>
    181 <span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a></span>
    182 <span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span><span class="ex">--88.87%--main</span></span>
    183 <span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span>          <span class="kw">|</span></span>
    184 <span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span>          <span class="kw">|</span><span class="ex">--19.84%--squareHelper</span><span class="er">(</span><span class="ex">unsigned</span> int<span class="kw">)</span></span>
    185 <span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span>          <span class="kw">|</span>          <span class="kw">|</span></span>
    186 <span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span>          <span class="kw">|</span>           <span class="ex">--4.99%--square</span><span class="er">(</span><span class="ex">unsigned</span> int<span class="kw">)</span></span>
    187 <span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span>          <span class="kw">|</span></span>
    188 <span id="cb4-11"><a href="#cb4-11" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span>          <span class="kw">|</span><span class="ex">--19.55%--factorial</span><span class="er">(</span><span class="ex">unsigned</span> int<span class="kw">)</span></span>
    189 <span id="cb4-12"><a href="#cb4-12" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span>          <span class="kw">|</span></span>
    190 <span id="cb4-13"><a href="#cb4-13" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span>           <span class="ex">--10.07%--square</span><span class="er">(</span><span class="ex">unsigned</span> int<span class="kw">)</span></span>
    191 <span id="cb4-14"><a href="#cb4-14" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span></span>
    192 <span id="cb4-15"><a href="#cb4-15" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span><span class="ex">--5.02%--squareHelper</span><span class="er">(</span><span class="ex">unsigned</span> int<span class="kw">)</span></span>
    193 <span id="cb4-16"><a href="#cb4-16" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span></span>
    194 <span id="cb4-17"><a href="#cb4-17" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span><span class="ex">--4.98%--square</span><span class="er">(</span><span class="ex">unsigned</span> int<span class="kw">)</span></span>
    195 <span id="cb4-18"><a href="#cb4-18" aria-hidden="true" tabindex="-1"></a><span class="kw">|</span></span>
    196 <span id="cb4-19"><a href="#cb4-19" aria-hidden="true" tabindex="-1"></a><span class="ex">--1.13%--factorial</span><span class="er">(</span><span class="ex">unsigned</span> int<span class="kw">)</span></span>
    197 <span id="cb4-20"><a href="#cb4-20" aria-hidden="true" tabindex="-1"></a><span class="ex">...</span></span></code></pre></div>
    198 <p>I often find the <code>--stdio</code> command difficult to read because the report can get wide for non-trivial programs, and horizontal navigation in the terminal is unergonomic.</p>
    199 <p>The final command worth mentioning is:</p>
    200 <pre><code>perf stat ./ex1
    201 
    202  Performance counter stats for &#39;./ex1&#39;:
    203 
    204                  0      context-switches:u              #      0.0 cs/sec  cs_per_second
    205                  0      cpu-migrations:u                #      0.0 migrations/sec  migrations_per_second
    206                132      page-faults:u                   #      4.1 faults/sec  page_faults_per_second
    207          32,436.48 msec task-clock:u                    #      nan CPUs  CPUs_utilized
    208            356,775      branch-misses:u                 #      0.0 %  branch_miss_rate           (88.89%)
    209     63,706,083,988      branches:u                      #   1964.0 M/sec  branch_frequency       (88.89%)
    210    134,126,037,336      cpu-cycles:u                    #      4.1 GHz  cycles_frequency         (88.89%)
    211    300,951,617,557      instructions:u                  #      2.2 instructions  insn_per_cycle  (88.89%)
    212          TopdownL1                                      #      4.4 %  tma_backend_bound
    213                                                         #     61.4 %  tma_bad_speculation        (88.89%)
    214                                                         #      0.0 %  tma_frontend_bound         (77.78%)
    215                                                         #     34.2 %  tma_retiring               (88.89%)
    216 
    217       32.440411262 seconds time elapsed
    218 
    219       32.234190000 seconds user
    220        0.002939000 seconds sys</code></pre>
    221 <p>Which provides high level information about the program’s entire execution.</p>
    222 <p>This is the command I run most frequently when validating optimizations that target functions making up a sizeable percentage of the program’s CPU usage. If the program is uniformly expensive across many functions, <code>perf stat</code> is less useful than a full report / flamegraph.</p>
    223 <h2 id="case-study">Case Study</h2>
    224 <h3 id="amfora">Amfora</h3>
    225 <p><a href="https://github.com/makew0rld/amfora">Amfora</a> is a fancy terminal-based Gemini protocol browser with syntax highlighting. Gemini is a text-based protocol which primarily distributes <a href="https://geminiprotocol.net/docs/gemtext.gmi">gemtext</a> documents. These documents use a similar syntax to markdown, but it’s slightly simpler. I chose to profile this program because software in the Gemini ecosystem is often simple to understand, making it great for educational use cases.</p>
    226 <p>When I start profiling software I often find it useful to use an oracle to understand what’s possible. An oracle in this context is a program that performs comparable tasks with decent performance characteristics. I chose <a href="https://git.laack.co/foreseen/">Foreseen</a>, a Gemini protocol browser I developed, as the oracle because it fulfils both criteria.</p>
    227 <p>I like to start by searching for worst case performance scenarios. Worst cases are often an amplification of an average case, so by improving worst case performance we can often improve the average case.</p>
    228 <p>To start our quest to find worse case scenarios for Amfora, we’ll load a large text file from disk, killing the program once the first lines of text are drawn in the terminal. Since neither browser supports text streaming, they both have to load and parse the document and then send text to the terminal, making this is a fair comparison. To generate a baseline document I executed the following Python code:</p>
    229 <div class="sourceCode" id="cb6"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="cf">with</span> <span class="bu">open</span>(<span class="st">&quot;lf.txt&quot;</span>, <span class="st">&quot;w&quot;</span>) <span class="im">as</span> f:</span>
    230 <span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>    <span class="cf">for</span> i <span class="kw">in</span> <span class="bu">range</span>(<span class="dv">0</span>,<span class="dv">200000</span>):</span>
    231 <span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>        f.write(<span class="bu">str</span>(i) <span class="op">+</span> <span class="st">&quot;</span><span class="ch">\n</span><span class="st">&quot;</span>)</span></code></pre></div>
    232 <p>The resulting file was ~1.3MB in size. I then ran both programs killing each program with Ctrl-C at first draw.</p>
    233 <pre><code>perf stat amfora lf.txt
    234 
    235 Performance counter stats for &#39;amfora lf.txt&#39;:
    236 
    237                  0      context-switches:u               #      0.0 cs/sec  cs_per_second
    238                  0      cpu-migrations:u                 #      0.0 migrations/sec  migrations_per_second
    239              2,742      page-faults:u                    #   9306.7 faults/sec  page_faults_per_second
    240             294.63 msec task-clock:u                     #      nan CPUs  CPUs_utilized
    241          1,052,499      branch-misses:u                  #      0.2 %  branch_miss_rate           (90.02%)
    242        575,712,764      branches:u                       #   1954.1 M/sec  branch_frequency       (89.14%)
    243        955,922,330      cpu-cycles:u                     #      3.2 GHz  cycles_frequency         (87.42%)
    244      2,669,651,845      instructions:u                   #      2.8 instructions  insn_per_cycle  (88.36%)
    245          TopdownL1                                       #      6.7 %  tma_backend_bound
    246                                                          #     24.9 %  tma_bad_speculation        (90.11%)
    247                                                          #     16.4 %  tma_frontend_bound         (79.92%)
    248                                                          #     52.0 %  tma_retiring               (90.37%)
    249 
    250        0.473990805 seconds time elapsed
    251 
    252        0.272938000 seconds user
    253        0.021266000 seconds sys
    254 </code></pre>
    255 <pre><code>perf stat foreseen lf.txt
    256 
    257  Performance counter stats for &#39;foreseen lf.txt&#39;:
    258 
    259                  0      context-switches:u               #      0.0 cs/sec  cs_per_second
    260                  0      cpu-migrations:u                 #      0.0 migrations/sec  migrations_per_second
    261              8,936      page-faults:u                    # 104842.2 faults/sec  page_faults_per_second
    262              85.23 msec task-clock:u                     #      nan CPUs  CPUs_utilized
    263            209,148      branch-misses:u                  #      0.1 %  branch_miss_rate           (88.30%)
    264        176,970,330      branches:u                       #   2076.3 M/sec  branch_frequency       (88.29%)
    265        248,919,966      cpu-cycles:u                     #      2.9 GHz  cycles_frequency         (88.29%)
    266        736,194,375      instructions:u                   #      3.0 instructions  insn_per_cycle  (88.99%)
    267          TopdownL1                                       #      3.9 %  tma_backend_bound
    268                                                          #     29.7 %  tma_bad_speculation        (89.50%)
    269                                                          #     21.2 %  tma_frontend_bound         (77.84%)
    270                                                          #     45.2 %  tma_retiring               (88.33%)
    271 
    272        0.354029324 seconds time elapsed
    273 
    274        0.066861000 seconds user
    275        0.021186000 seconds sys</code></pre>
    276 <p>This is very unscientific, especially given I was watching to see when to kill the programs, but this is how I normally start profiling. We can’t conclude anything from these results as the timings are within margin of error.</p>
    277 <p>Since Amfora can highlight code let’s see how that impacts performance. I pasted the Python code above at the top of the text file, encapsulated by gemtext preformatted text lines, and then renamed the file to <code>lf.gmi</code>. We then find:</p>
    278 <pre><code>perf stat amfora lf.gmi
    279 
    280  Performance counter stats for &#39;amfora lf.gmi&#39;:
    281 
    282                  0      context-switches:u               #      0.0 cs/sec  cs_per_second
    283                  0      cpu-migrations:u                 #      0.0 migrations/sec  migrations_per_second
    284            900,174      page-faults:u                    #  12090.4 faults/sec  page_faults_per_second
    285          74,453.35 msec task-clock:u                     #      nan CPUs  CPUs_utilized
    286        229,042,926      branch-misses:u                  #      0.4 %  branch_miss_rate           (88.94%)
    287     62,713,218,442      branches:u                       #    842.3 M/sec  branch_frequency       (88.85%)
    288    153,193,058,619      cpu-cycles:u                     #      2.1 GHz  cycles_frequency         (88.97%)
    289    306,159,421,078      instructions:u                   #      2.0 instructions  insn_per_cycle  (88.90%)
    290          TopdownL1                                       #      0.6 %  tma_backend_bound
    291                                                          #     97.8 %  tma_bad_speculation        (88.83%)
    292                                                          #     -0.1 %  tma_frontend_bound         (77.86%)
    293                                                          #      1.7 %  tma_retiring               (88.91%)
    294 
    295       28.983517177 seconds time elapsed
    296 
    297       63.894262000 seconds user
    298        8.207151000 seconds sys</code></pre>
    299 <pre><code>perf stat foreseen lf.gmi
    300 
    301  Performance counter stats for &#39;foreseen lf.gmi&#39;:
    302 
    303                  0      context-switches:u               #      0.0 cs/sec  cs_per_second
    304                  0      cpu-migrations:u                 #      0.0 migrations/sec  migrations_per_second
    305              6,551      page-faults:u                    #  90396.7 faults/sec  page_faults_per_second
    306              72.47 msec task-clock:u                     #      nan CPUs  CPUs_utilized
    307            154,134      branch-misses:u                  #      0.1 %  branch_miss_rate           (88.98%)
    308        166,258,529      branches:u                       #   2294.2 M/sec  branch_frequency       (88.99%)
    309        232,523,911      cpu-cycles:u                     #      3.2 GHz  cycles_frequency         (88.96%)
    310        705,288,446      instructions:u                   #      3.0 instructions  insn_per_cycle  (88.93%)
    311          TopdownL1                                       #      7.6 %  tma_backend_bound
    312                                                          #     23.2 %  tma_bad_speculation        (88.96%)
    313                                                          #     18.8 %  tma_frontend_bound         (77.41%)
    314                                                          #     50.4 %  tma_retiring               (88.45%)
    315 
    316        0.381682961 seconds time elapsed
    317 
    318        0.058132000 seconds user
    319        0.015949000 seconds sys</code></pre>
    320 <p>That’s a lot slower for Amfora, ~76x slower than Foreseen, and ~61x slower than it was with the normal text file. Let’s look at a flamegraph for this.</p>
    321 <object data="/images/amfora-before.svg" type="image/svg+xml" width="100%">
    322 </object>
    323 <p>So 68.34% of samples occurred while executing the GC. That’s a bit surprising as there shouldn’t be that many allocations occuring. We also see 25.47% of the samples occur when executing the RenderGemini function. Of this, most of it is spent on concatstring3, a function used to concatenate strings.</p>
    324 <p>Looking in the RenderGemini function for string concatenations we find:</p>
    325 <pre><code>rendered += fmt.Sprintf(&quot;[%s]&quot;, config.GetColorString(&quot;preformatted_text&quot;)) +
    326     buf + fmt.Sprintf(&quot;[%s:%s:-]\r\n&quot;, config.GetColorString(&quot;regular_text&quot;), config.GetColorString(&quot;bg&quot;))
    327 
    328 ...
    329 
    330 rendered += buf + &quot;\r\n&quot;
    331 
    332 ...
    333 
    334 rendered += ren
    335 
    336 ...
    337 
    338 buf += strings.TrimSuffix(lines[i], &quot;\r&quot;) + &quot;\r\n&quot;</code></pre>
    339 <p>Yeah, this isn’t great. Each of these seemingly innocuous appends is very costly. Go strings are immutable so each append creates an entirely new string, and since we accumulate into <code>buf</code> until reaching a preformatted text switch line (“```” lines), we have to re-create the accumulator string 200,000 times to parse our file.</p>
    340 <p>Fortunately, this is easy to solve by using a strings.Builder which doesn’t have this issue, and that’s <a href="https://github.com/makew0rld/amfora/pull/370/changes">what I did</a>. After this change, we can perform our profiling again to find:</p>
    341 <pre><code>perf stat amfora lf.gmi
    342 
    343  Performance counter stats for &#39;amfora lf.gmi&#39;:
    344 
    345                  0      context-switches:u               #      0.0 cs/sec  cs_per_second
    346                  0      cpu-migrations:u                 #      0.0 migrations/sec  migrations_per_second
    347              6,039      page-faults:u                    #   4871.9 faults/sec  page_faults_per_second
    348           1,239.55 msec task-clock:u                     #      nan CPUs  CPUs_utilized
    349          3,631,996      branch-misses:u                  #      0.1 %  branch_miss_rate           (89.02%)
    350      3,017,891,055      branches:u                       #   2434.7 M/sec  branch_frequency       (88.96%)
    351      4,654,531,574      cpu-cycles:u                     #      3.8 GHz  cycles_frequency         (88.93%)
    352     14,168,541,807      instructions:u                   #      3.1 instructions  insn_per_cycle  (88.81%)
    353          TopdownL1                                       #      2.2 %  tma_backend_bound
    354                                                          #     36.9 %  tma_bad_speculation        (88.80%)
    355                                                          #     18.5 %  tma_frontend_bound         (77.83%)
    356                                                          #     42.5 %  tma_retiring               (88.90%)
    357 
    358        1.185772969 seconds time elapsed
    359 
    360        1.193871000 seconds user
    361        0.039062000 seconds sys</code></pre>
    362 <p>This is much better. We are now using ~33x less cycles, and it’s ~25x faster than before. It’s also only 3x slower than foreseen on this task.</p>
    363 <object data="/images/amfora-after.svg" type="image/svg+xml" width="100%">
    364 </object>
    365 <p>Looking again at the flamegraph, we see the RenderGemini function is now mostly performing word wrapping, and the GC is only utilizing the CPU during 16.48% of our samples.</p>
    366 <p>We could continue identifying hotspots, but now there are 4 ~equally costly groupings, and as performance becomes more diffuse, optimizations will generally have a smaller impact on overall performance, so I’m going to leave this as is.</p>
    367 <h2 id="whats-next">What’s Next</h2>
    368 <p>This post only discussed on-CPU profiling for program execution. There are a few additional metrics worth profiling that I’ll discuss in the future:</p>
    369 <ol type="1">
    370 <li>Off-CPU profiling</li>
    371 <li>Memory profiling</li>
    372 <li>Build time profiling</li>
    373 </ol>
    374 </body>
    375 </html>