blog

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

commit 7485e17dfc712fee70a1ee4adcefe26f4dba4b94
parent 6c28d638d8886e07e7911dd946b31155ca0479f2
Author: Andrew Laack <andrew@laack.co>
Date:   Sat, 17 Oct 2026 15:39:14 -0500

Finished writing

Diffstat:
Mposts/wip/basic-software-profiling-cpu-usage.md | 125++++++++++++++++++++++++++++++++++---------------------------------------------
Mposts/wip/posix-shell-jobs.md | 10+++++-----
2 files changed, 59 insertions(+), 76 deletions(-)

diff --git a/posts/wip/basic-software-profiling-cpu-usage.md b/posts/wip/basic-software-profiling-cpu-usage.md @@ -1,18 +1,18 @@ # Basic Software Profiling: CPU Usage -Tens of millions of human hours are wasted every day because software is slow. The most addressable contributing factor to this state of affairs is education. A specific educational problem is a lack of awareness for how to profile software. +Software today is much slower than it should be. I believe this is, in part, because most software developers do not understand performance. -To this end, this post will explain how you can find the parts of programs hogging the most CPU time. This post will focus on compiled programs, but the core ideas may be applied to interpreted programs. +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. ## Tools -[Perf](https://en.wikipedia.org/wiki/Perf_%28Linux%29) 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 dedicated tools exist for many interpreted languages to collect call stack information. +[Perf](https://en.wikipedia.org/wiki/Perf_%28Linux%29) 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. -[Flamegraph](https://github.com/brendangregg/FlameGraph) is a suite of tools for generating flamegraphs, a type of graph designed for the visualization of performance data. I use my [fork of flamegraph](https://git.laack.co/flamegraph) which doesn't add j***s***** to generated SVGs, but apart from this they function identically. +[Flamegraph](https://github.com/brendangregg/FlameGraph) is a suite of tools for generating flamegraphs, a type of graph designed for the visualization of performance data. I'll be using my [fork of flamegraph](https://git.laack.co/flamegraph) which doesn't add j***s***** to generated SVGs, but apart from that they function identically. ## Reading a Flamegraph -Take a look at the flamegraph below and try to understand the performance characteristics of the program: +Look at the flamegraph and try to understand the performance characteristics of the program: <object data="/images/ex1-fg.svg" type="image/svg+xml" width="100%"></object> @@ -24,7 +24,7 @@ uint32_t square(uint32_t input) { return input * input; } -// to show stack depths +// helper function to show stack depths uint32_t squareHelper(uint32_t input) { uint32_t x = 100 * 100; return square(input); @@ -32,6 +32,7 @@ uint32_t squareHelper(uint32_t input) { uint32_t factorial(uint32_t input) { uint32_t acc = 1; + while(input > 1) { acc *= input; input -= 1; @@ -63,7 +64,7 @@ int main() { The amount of time spent with the `main` function on the call stack is represented by the width of its bar. -Notice how there are multiple bars that say `square`. This is because we execute `square` at different call stack depths, and the width of each bar is dictated by the amount of time we spent with `square` on the call stack at a given stack depth. +Notice how there are multiple bars that say `square`. This is because we execute `square` at different call stack depths, and the width of each bar is proportional to the amount of time we spent with `square` on the call stack at a given stack depth. 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 `squareHelper` and `square`, we see we spent more time executing `squareHelper` than `square`, evidenced by the fact that from a top-down view, `squareHelper` is wider. @@ -71,7 +72,7 @@ The astute among you might've noticed `square` and `squareHelper` seem to have b ## Perf -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 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. +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. This is the command I ran to generate the data: @@ -79,15 +80,13 @@ This is the command I ran to generate the data: perf record -g ./ex1 ``` -The `record` command is used to run a command and record its performance profile. These are written to the `perf.data` file. By default, `perf record` will sample at 1000Hz while the program is on-CPU. The final option, `-g`, is used to specify we are interested in having the call stack included in our data. +The `perf record` command is used to run a command and record its performance profile, which is written to the `perf.data` file. By default, `perf record` will sample at 1000Hz while the program is on-CPU. The final option, `-g`, is used to specify we are interested in having the call stack included in our data. To view aggregate information about the data in the `perf.data` file we can run: ```bash perf report -g -``` -``` + 100.00% 0.00% ex1 ex1 [.] _start + 100.00% 0.00% ex1 libc.so.6 [.] __libc_start_main + 100.00% 0.00% ex1 libc.so.6 [.] call_init (inlined) @@ -99,14 +98,13 @@ perf report -g ... ``` -If you are interested in information about which functions are calling each other, and the resulting on-CPU times therein, you can run this command: +If you are interested in information about which functions are calling each other, and the associated on-CPU times, you can run this command: ```bash perf report -g --stdio -``` -``` ... + |--88.87%--main | | | |--19.84%--squareHelper(unsigned int) @@ -125,15 +123,13 @@ perf report -g --stdio ... ``` -In many cases, I find the `--stdio` command a bit difficult to read because the report can get wide for non-trivial programs (there are additional CLI options that can help with this), and horizontal navigation in the terminal is unergonomic. +I often find the `--stdio` command difficult to read because the report can get wide for non-trivial programs, and horizontal navigation in the terminal is unergonomic. The final command worth mentioning is: ``` perf stat ./ex1 -``` -``` Performance counter stats for './ex1': 0 context-switches:u # 0.0 cs/sec cs_per_second @@ -157,28 +153,19 @@ perf stat ./ex1 Which provides high level information about the program's entire execution. -This is the command I run most frequently when validating optimizations when the optimization is aimed at improving the performance of a function that contributes a lot to the total program runtime. If the program is more uniformly expensive across many functions, `perf stat` is less useful than a full report / flamegraph. - -## What to Optimize - -Start with functions using lots of CPU time that you wouldn't expect to. Often a small number of functions do the majority of computation, and these are the ones worth optimizing in the average case. To make these functions run faster, you should consider the following: - -1. Can we call this function less often -2. Can each call perform less work - -Both of these questions are about decreasing work, not making the work faster. Making work faster can be complex, so it's often easier to improve performance by removing wasted work or making algorithmic improvements. +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, `perf stat` is less useful than a full report / flamegraph. ## Case Study ### Amfora -[Amfora](https://github.com/makew0rld/amfora) is a fancy terminal-based Gemini protocol browser with syntax highlighting. Gemini is a text-based protocol which primarily distributes [gemtext](https://geminiprotocol.net/docs/gemtext.gmi) documents. These documents use a similar syntax to markdown, but its 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. +[Amfora](https://github.com/makew0rld/amfora) is a fancy terminal-based Gemini protocol browser with syntax highlighting. Gemini is a text-based protocol which primarily distributes [gemtext](https://geminiprotocol.net/docs/gemtext.gmi) 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. 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 [Foreseen](https://git.laack.co/foreseen/), a Gemini protocol browser I developed, as the oracle because it fulfils both criteria. -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 you can often improve average case performance. +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. -Let's look for the worst case for the task of rendering a textual document. We'll load a large text file from disk using both browsers, killing the program once the first lines of text are drawn. Since neither browser supports text streaming, they will both have to load and parse the document, and then draw some text to the terminal. To generate the document I executed the following Python code: +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: ```python with open("lf.txt", "w") as f: @@ -186,7 +173,7 @@ with open("lf.txt", "w") as f: f.write(str(i) + "\n") ``` -The resulting file was ~1.3MB in size. I then ran both programs killing each program with Ctrl-C at first draw of the text from the file: +The resulting file was ~1.3MB in size. I then ran both programs killing each program with Ctrl-C at first draw. ``` perf stat amfora lf.txt @@ -237,33 +224,9 @@ perf stat foreseen lf.txt 0.021186000 seconds sys ``` -This is very unscientific, especially given I was eyeballing when to kill the programs, but that's how I normally start profiling. We can't conclude anything from these results yet as the timings are within margin of error. - -Since Amfora can highlight code, let's see how that impacts performance. I pasted the Python code block above at the top of the text file and then renamed the file to `lf.gmi`. We then find: - -``` -perf stat foreseen lf.gmi - - Performance counter stats for 'foreseen lf.gmi': - - 0 context-switches:u # 0.0 cs/sec cs_per_second - 0 cpu-migrations:u # 0.0 migrations/sec migrations_per_second - 6,551 page-faults:u # 90396.7 faults/sec page_faults_per_second - 72.47 msec task-clock:u # nan CPUs CPUs_utilized - 154,134 branch-misses:u # 0.1 % branch_miss_rate (88.98%) - 166,258,529 branches:u # 2294.2 M/sec branch_frequency (88.99%) - 232,523,911 cpu-cycles:u # 3.2 GHz cycles_frequency (88.96%) - 705,288,446 instructions:u # 3.0 instructions insn_per_cycle (88.93%) - TopdownL1 # 7.6 % tma_backend_bound - # 23.2 % tma_bad_speculation (88.96%) - # 18.8 % tma_frontend_bound (77.41%) - # 50.4 % tma_retiring (88.45%) - - 0.381682961 seconds time elapsed +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. - 0.058132000 seconds user - 0.015949000 seconds sys -``` +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 `lf.gmi`. We then find: ``` perf stat amfora lf.gmi @@ -289,13 +252,37 @@ perf stat amfora lf.gmi 8.207151000 seconds sys ``` +``` +perf stat foreseen lf.gmi + + Performance counter stats for 'foreseen lf.gmi': + + 0 context-switches:u # 0.0 cs/sec cs_per_second + 0 cpu-migrations:u # 0.0 migrations/sec migrations_per_second + 6,551 page-faults:u # 90396.7 faults/sec page_faults_per_second + 72.47 msec task-clock:u # nan CPUs CPUs_utilized + 154,134 branch-misses:u # 0.1 % branch_miss_rate (88.98%) + 166,258,529 branches:u # 2294.2 M/sec branch_frequency (88.99%) + 232,523,911 cpu-cycles:u # 3.2 GHz cycles_frequency (88.96%) + 705,288,446 instructions:u # 3.0 instructions insn_per_cycle (88.93%) + TopdownL1 # 7.6 % tma_backend_bound + # 23.2 % tma_bad_speculation (88.96%) + # 18.8 % tma_frontend_bound (77.41%) + # 50.4 % tma_retiring (88.45%) + + 0.381682961 seconds time elapsed + + 0.058132000 seconds user + 0.015949000 seconds sys +``` + 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. <object data="/images/amfora-before.svg" type="image/svg+xml" width="100%"></object> -So 68.34% samples occurred while executing the GC, that's a bit surprising, even given how awful garbage collectors are. We also see that 25.47% of the time, most of the remaining time, is spent in the RenderGemini function. Of this, most of it is spent on concatstring3, a function under the hood that's used to concatenate strings. +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. -Here's where that'd be used in the function: +Looking in the RenderGemini function for string concatenations, we find: ``` rendered += fmt.Sprintf("[%s]", config.GetColorString("preformatted_text")) + @@ -314,11 +301,9 @@ rendered += ren buf += strings.TrimSuffix(lines[i], "\r") + "\r\n" ``` -Well, there's our problem; 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 `buf` until reaching a preformatted text switch line ("```" lines), the file we were trying to open has to re-create the full string 200,000 times, since the tail 200,000 lines in the file don't have any format switch lines. - -This is relatively trivial to solve by using a strings.Builder which doesn't have this issue, and that's [what I did](https://github.com/makew0rld/amfora/pull/370/changes)*. After this change, we can perform our profiling again to find: +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 `buf` until reaching a preformatted text switch line ("```" lines), we have to re-create the accumulator string 200,000 times to parse our file. -(NOTE: The numbers I referenced in the PR differ from what's shown here, but they're similar) +Fortunately, this is easy to solve by using a strings.Builder which doesn't have this issue, and that's [what I did](https://github.com/makew0rld/amfora/pull/370/changes)*. After this change, we can perform our profiling again to find: ``` perf stat amfora lf.gmi @@ -344,20 +329,18 @@ perf stat amfora lf.gmi 0.039062000 seconds sys ``` -Much better, that's now using 32x less cycles, and is far faster than before. It's also only 3x slower than foreseen on this specific task. This tells me there are further optimizations that can be performed, but I believe we've fixed the most obvious issue. +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. <object data="/images/amfora-after.svg" type="image/svg+xml" width="100%"></object> -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, much better. - -We can go deeper still on this, but there are now 3 ~equally costly groupings, and as performance becomes more diffuse, optimizations will generally have a smaller amount of impact on performance, so we can leave this where it is. Additional optimizations would also require more investment in instrumentation to support profiling, but I believe most people don't have to go that far since we've seen there are often low hanging fruit that are so obviously incorrect that we don't have to get very scientific to show tangible improvements. +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. -(Relevant [XKCD](https://xkcd.com/2400/)) +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. ## What's Next -This post only discussed on-CPU time profiling for program execution. There are a few additional metrics worth profiling that I'll discuss in the future: +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: -1. Off CPU profiling +1. Off-CPU profiling 2. Memory profiling -3. Build profiling +3. Build time profiling diff --git a/posts/wip/posix-shell-jobs.md b/posts/wip/posix-shell-jobs.md @@ -8,11 +8,11 @@ It turns out POSIX shell has a lot of this built in. ## The Stack - st -- bash / dash / ash -- optional: abduco +- dash +- abduco (optional) -That's it. That's all you need to have the same features as tmux, zellij, -ghostty (gross) all in one. +That's it. That's all you need to reach useful feature parody with tmux, zellij, +ghostty (gross), and zsh / fish all in one. ## Writing Code @@ -23,7 +23,7 @@ does everything instead of dealing with the bloated monstrosity that is tmux. Instead I do this: -- write code in vim +- write code in vim / kakoune / vi / nvi - C-z it to suspend the program - Run my commands in the newly cleaned bash session - Run 'fg' to foreground the suspended session.