This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com
Last night we did this live session on performance engineering. I’ve done sessions on 1BRC in the past as well, but this time the focus was on learning things at a more fundamental level. We spent a good chunk of the time in the beginning understanding the basics of how the CPU executes code, how the data cache when utilized efficiently improves program performance significantly, and touched upon the branch predictor and instruction level parallelism.
After that we discussed the optimization techniques that winners of 1BRC used. These included:
* An analysis of read and mmap system calls, how they work under the hood and their trade offs
* Static partitioning versus work stealing when distributing work in a multithreaded solution
* Cost of branch misses in a hot loop and a cool branchless coding technique to find delimiters in strings
* Why a shared data structure might be bad in a multithreaded system
* Design of a cache efficient hash table
* Loop unrolling to improve the performance by 3x
I hope you enjoy the recording. Pro tip: watch it at 1.5x or 2x speed.
The real benefit of these sessions is in attending live because you get to ask questions and drive the discussion. However, if you wish to access the recording and don’t want a subscription, you can purchase it at the below link.
Note to attenddees: We discussed SWAR but I did not explain the code because doing that would have taken a lot of time. However, for those interested can check out this blog post.
Audio and video play straight from the show's own hosting. PodSubs stores and serves no media.
Transcript
From the show. Tap a time to play from there.
SPEAKER_00Okay, we can start now. So we are going to talk about some of the interesting performance optimization lessons that came out of the 1 billion row challenge.
SPEAKER_00So I'm not really sure how many people have participated or have heard about it. So I'm just going to give a brief recap about what the competition was all about.
SPEAKER_00Let me try this. So the 1 billion road challenge was a competition which was organized somewhere last year, a few months back. So the idea was that you have a file which consists of 1 billion records and it's a plain text file. Each record in the file is one line and there are two values in one record.
SPEAKER_00So there is a location name and there is a temperature value, and these are separated by a semi-colon. So what you have to do is you have to pass the file, read for each location. You have to find out its minimum, maximum and average Uh, temperature value across the file. So in, within the file, uh, the location name might be repeated several times. So one location might have several, uh, reports in the file.
SPEAKER_00So you would have to take care of that. So you would have to consolidate the records for one location and you have to find out for each location, what is its overall min max and average values of the temperature. And. Uh, they were, they could be at max 10,000 unique location names and the temperature values would be in the range of minus 99.9 to 99.9.
SPEAKER_00So those were the conditions. And one of the other thing was that you had to implement it in Java. Um, and. By the end of the competition, so I think surprisingly, no one really expected, but the top solutions were able to run to perform this task in less than a second. So, and there were a lot of interesting tricks that people used to achieve this level
SPEAKER_00of performance from Java. And so that's what I want to cover in this talk. So what were those interesting performance optimization techniques that people came up with and what were the ideas behind those techniques? Now I have done this session similar kind of thing in the past as well. So usually in the past what I have done is I have gone through the code. So I have gone through an implementation of this challenge and I have explained various things or how would you go from a naive implementation to a very optimal
SPEAKER_00implementation which would be able to run in close to one second of time. But this time I want to go do it slightly differently. So I want to focus on the underlying principles which are behind these ideas, behind these performance tricks. And if you understand those tricks, then it's very straightforward to understand a specific implementation of that performance technique and so we will maybe we will take a look at the specific code as well but I will want to focus on the key
SPEAKER_00principles and the other thing I want to do is I want to make this very interactive so please be ready if I ask questions please just feel free to answer there is no Right or wrong here, basically performance optimization is all about making a reasonable guess. So based on what information that you have, based on that, you have to guess what might be a bottleneck or what, how could you optimize something? So I just will just make it interactive.
SPEAKER_00So this is, uh, If you had to implement it yourself, this is the outline of the algorithm. So you will have to read lines from the file. And then for each line, you would have to parse the location name and the temperature value. And this is a plain text file. Everything is a string. And it's a UTF-18 protein string if you want to care about that. So once you have the location name and temperature value for a line, then you have to update the report for that location. So you would have some kind of a data structure where you would maintain what is
SPEAKER_00the current min, max, and average temperature for that location. And then you would have to go and update that. And then you repeat for the next line. So you continue doing that. So that's the algorithm. Basically there are three steps and then for each step, there are things that you have to think about from the performance point of view. So when you have to read lines from a file, how do you read those? Uh, so typically there are two ways to read data from a file.
SPEAKER_00You can use the read system call, or you can use memory mapping. So yes, one thing is read better than a map or, or is it the other way around? So that is one of the key questions. Usually you have to decide based on the kind of workload that you have. Again, so that requires that you understand how a read works, how a map works so that you can make that informed decision about that. Then the second thing is if you're going to use multiple threads to do this job
SPEAKER_00in parallel, then how do you distribute the work between the threads? So that is another question. And there are various strategies that you can think about. Again, that comes down to the nature of the work and how do you efficiently utilize the hardware. So that is one of the two of the key things we are going to learn about. Then when you're passing the strings,
SPEAKER_00For example, here we will have to parse. We will be reading bytes from the file and then we have to find a new line boundary. So where is the new line in this set of bytes that you have read? And then once you have found a new line boundary, then you have to find a semicolon because the location name and the temperature values are split by semicolons. How do you find a semicolon. So usually your split method, for example, Java gives you the split method where you can say s.split and whatever delimiter
SPEAKER_00you want to give. So usually that is not very efficient when it comes to this level of performance that we want to achieve. So we are going to talk about how can we do that. what are the bottlenecks there and then how can we optimize that and finally updating the report for the location so here again we will run into concurrency issues so if you are using multiple threads how do you synchronize that data which is spread up between the threads and how do you take advantage of cache so when i
SPEAKER_00say cache i'm talking about the cpu cache so the These are the six key questions that we are going to dive into as we go forward. So these are the things that I want to cover. But before we start, as I said, I want to go from the fundamentals and I want those to be clear so that when we get into the specifics, We will know exactly what are the bottlenecks and why those specific optimizations
SPEAKER_00are actually working that the winners of the competition implemented. In terms of fundamentals, the whole field of performance optimization lies on this concept of mechanical sympathy. Basically, the idea is that you have to understand the abstractions on top of which your code
SPEAKER_00is running. So there are things like your hardware is there, then On top of that, your operating system kernel is running. And then on top of that, your compiler and the runtime are present. And then comes your application code. So until you understand how these layers beneath your code are interacting with each other and how they're executing your code, you will not have any clue how to optimize your code because the bottlenecks lie
SPEAKER_00all in these layers. And this is very similar to how an F1 driver has, even though an F1 driver doesn't have to know the nuts and bolts of his engine, but he has to understand how the engine works so that he knows what's the optimal time to switch gears and how to avoid overheating of the engine and be fuel efficient and all those things. So that requires an understanding of the machine.
SPEAKER_00And then doing actions which are in sync with how the machine works. And as long as you are in harmony with the machine, you will be able to achieve performance. Now, keeping that in mind, I want to talk about some of the fundamentals about how the processor executes a code. So now there's a ton of details that we could get into, but I want to focus on three main things which are going to be
SPEAKER_00used as we get into the specific optimizations as well. So these are the three things. How to optimally, how does the CPU's data cache works and how can we use it optimally? So that is one thing. The other thing is, how does the branch predictor work? And what are the, costs of missing a branch when the branch predictor makes a mistake,
SPEAKER_00what are the costs associated with it? How does it impact the code? And finally, we'll touch upon just a bit on instruction level parallelism. So how can we take advantage of that? So these are the three things we need to understand before we get into all the optimization specific to OneBRC. So typically, our program lives as a binary file somewhere on the disk.
SPEAKER_00For example, on the left, I have some example program, and this is assembly just to show that because if you use a compiled language, it will generate machine code. And although machine code is basically binary, but here I'm just for just readability, I'm showing the assembly code. And when you want to execute that program, uh, the operating system kernel will load it into memory and it will organize it into a
SPEAKER_00specific layout. So on the right hand side, this is the typical memory layout of a process and It is organized in the form of segments. So you have the text segment, the data segment, the VSS segment, and then you have the memory region stack and heap. So all the executable instructions of your program are mapped in the text section and all the data of your program is usually in the data section.
SPEAKER_00And then the stack is where when you when any function in your code executes all the local variables and function arguments, all those things will go on to the stack. And then heap is where all your dynamically allocated memory goes. Now, what this means is that the operating system will load this binary into memory. And which means all of this is your main memory. And then
SPEAKER_00this is your CPU. So main memory and CPU are not together. So there is a, these are two different parts inside your hardware. And usually there is some sort of communication link between the processor and the main memory. And in order to execute that program, all that instruction and data has to move into the processor so that the processor can start executing it. And typically there is a latency of 200 to 300 CPU cycles
SPEAKER_00in moving data from the main memory into the CPU, which means if the CPU has to wait 200 cycles for each instruction and data to move into the CPU, our program will take forever to finish execution. So all the, Hardware designers have over the decades that they have spent a lot of time in trying to hide this slow memory access latency and all the optimization, all the performance optimization that you,
SPEAKER_00that is out there in the world. Most of it just boils down to how can you avoid this, uh, latency of reading data from the memory. So basically the answer lies in cache. Uh, so the CPU designers, they came up with the idea of dash. So they introduced caches in the code and basically the frequently used data will usually live in the gas so that the CPU doesn't really have to wait 200 cycles to
SPEAKER_00execute any instruction. And which thanks to work quite well, as long as your code is able to take advantage of that. Now, how do we take advantage of that? To do that, we have to understand how the cache works and how the CPU tries to use it. So let's get into that. So I'm going to take a made up example here. It is very important that we understand this because most of the things that we're going to
SPEAKER_00Uh, discuss later on is all based on efficiency of cash utilization. So let's take an example here. So we have a very simple CPU. It has a frequency of one gigahertz. So let's, which means that, uh, it can execute 1 billion cycles per second. And let's also assume that it can do one instruction per cycle. So, uh, Yeah, it can execute one instruction per cycle. And let's assume that reading any piece of data from the main memory takes a hundred cycles.
SPEAKER_00Okay. So I have a very simple program here. So I'm taking, um, I'm using C here because the things that I want to talk about, I think I didn't want to go into any other language here. I think most of the people understand C. So let me just explain. So you have a very simple function here, where cat two here, which takes a pointer to a vector here. And what it does is it runs through each element of that vector and increments it by two.
SPEAKER_00So, uh, this is a pointer. That means the vector is allocated somewhere in the memory. So for example, you can think this block is that vector, and this is of size 1 billion. So there is a one GB memory allocated here. So from zero to 1 billion, and now this is the. compiled assembly code. You don't really have to understand the assembly here. I have highlighted the equivalent part here.
SPEAKER_00So the yellow part here, so here is the loop body. So basically it is in, um, incrementing the loop counter, comparing it with the value, the max size of the array, which is 1 billion. So if we have reached that value, um, we will return otherwise we'll jump back to this address which is again the body of
SPEAKER_00the loop now what we are doing in the body of the loop is the critical part that i want to focus on this first instruction the move instruction so what it is saying is we have to move this first element of the array into the CPU. So this move instruction, what it is going to do is RDI points to, RDI is a register here and RAX acts as a loop counter. So RDI contains the address of this array.
SPEAKER_00So it points here. and RAX would be initialized to zero. So when you have this assembly instruction where the two registers are in parenthesis, basically you're trying to compute an address and then try to dereference that address. So what this means is read the address at RDI plus RAX. So RDI is this and RAX is zero, so that means read the first element. Read it and bring it into the ADX register, which is another register here. So first we have to read that value from memory into the register.
SPEAKER_00Then we have the add instruction. So we are adding whatever value we read, we are adding two to it. And then another move instruction, which is saying, write that value back into the same memory location. Is this part clear if you have questions, any instructions are not clear.
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the last video, we learned about copy-on-write (CoW) and understood its mechanics by digging inside the mmap pathway in the...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the last video, we discussed demand paging. Now, let’s move towards an even more interesting topic: copy-on-write (CoW). Just...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the previous video in our virtual memory series, we discussed demand paging. But that was mostly theoretical, explaining how...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com Welcome back to the video series on virtual memory based on my article on the same topic. It is also available in ebook format on...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com This is a short aside in our virtual memory series. We have talked extensively about the size of a virtual address and the virtual...