Compiler Aware Programming Optimizations
You might underestimate it, but your compiler does a LOT! Apart from just converting your high-level language (HLL) program into assembly language, it constantly looks for optimizations to reduce the number of CPU cycles required to run your code. Although it does a pretty good job, it can only do so much and often runs into optimization blockers. However, we can help compilers A LOT by adopting a few subtle programming practices. They won't improve algorithmic efficiency or anything, but they'll take your implementation of the algorithm to a highly optimized level!
Required Prerequisites
- Understanding of Time Complexity and the Big-O Notation
- Basic knowledge or intuition of computer architecture (pipelining, caching, control flow, etc.)
- Familiarity with C++
Introduction
According to the Big-O Notation:
Graphically, we can represent this as shown below:
When programming, the algorithm you choose makes the most significant contribution to efficiency. For example, irrespective of whether you have redundant loops and condition checks all over your code, an algorithm running in O(logN) time will run better than an algorithm executing in O(N) time in the long run. So, as a programmer, your foremost priority should always be choosing appropriate data structures and efficient algorithms. But once you have selected an optimal algorithm, there are still things you can do to optimize your code even further. It won't bring the time complexity down from, say, O(N) to O(logN), but it can drastically change the value of 'c' defined earlier in the formula of the Big-O Notation. So how do we do this?
To understand these optimizations, we have to look from the perspective of a compiler. A compiler and assembler jointly work to convert your program written in a high-level language (HLL) like C/C++, Python, Java, etc., to machine code, which is then executed in a pipelined fashion by the computer's processor. The critical word here is pipelined. Your compiler constantly looks for optimizations like instruction reordering, register allocation, and inefficiency reduction to bring the effective cycles per instruction of the program as close to one as possible. Compilers even have optimization levels that correspond to different aggression levels they can work at. For example, in C, you can specify different levels of optimizations you want the compiler to work at using the -o1, -o1, or -o3 levels in GCC. You can read more about this in the link given below.
Even with all of the compiler's power, it's sometimes helpless as it can't do any better without the help of the programmer. Thus, as programmers, we are responsible for writing code, keeping the compiler in mind, and trying to make its job as easy as possible. We can do this by adopting the following practices:
- Concurrent programming
- Sharing common subexpressions
- Using basic ALU operations most of the time
- Minimizing procedure calls
- Getting rid of unnecessary memory references
- Decreasing dependency between different instructions
- Utilizing spatial and temporal locality
These optimizations will reasonably ease the compiler's work and increase program efficiency, even if it is just marginally. However, even with these optimizations, the compiler sometimes can't do anything because of optimization blockers. Two of these blockers include the ones mentioned below.
- Potential memory aliasing
- Potential procedure call side effects
We'll go through all the optimizations and blockers with examples to illustrate how they work and can be exploited.
Concurrent Programming
In 2001, IBM introduced the first multicore processor (2 64-bit microprocessors), and the world has never looked back. A lot of computation in a program can be split up into multiple independent (or almost independent) sub-tasks that should be exploited to the maximum.
Programmers should use every opportunity to parallelize code and run smaller program segments simultaneously using different threads on multiple cores and processors. Though doing this doesn't help the compiler, it incorporates long-term benefits that only increase efficiency.
Sharing Common Subexpressions
Sometimes, we unknowingly or knowingly promote the recomputation of specific values, which are repeatedly reused. For example, look at the C++ code below, where we observe the corners surrounding a pixel of an index (n1*x,n2*y) stored in a 2D array 'arr.'
In this example, we are making the compiler recompute the value of n1*x & n2*y four times each when we could enable it to do it only once by storing the values in variables. This would effectively reduce 6 ALU operations. Thus, the optimal way of going about this program can be seen in the corrected code below.
Using Simple ALU Operations
Some ALU operations are more expensive than others. Generally, multiplication and division require more computation than addition, subtraction, logic gates, and other bit manipulations. Though it's inevitable sometimes to use multiplication and division in their standard forms, we can frequently adopt certain tricks to make use of the fact that some ALU operations are computationally cheaper. Some examples are shown in the code snippet below.
Again, this isn't directly related to the compiler but is a practice you should keep in mind while coding. It might reduce code readability slightly but provides a reasonable tradeoff, especially if you use multiple such operations repeatedly throughout your program.
Minimizing Procedure Calls
As programmers, we often tend to specify unnecessary procedures or function calls. In some places, they make sense, but in others, they are redundant and increase computation for no reason. For example, look at the code snippet below, where we calculate the sum of elements in a C++ vector.
The problem with this method is that for iteration, we call a function to recompute the size of the vector. The compiler can't assume that the vector's length remains constant throughout the loop and thus can't omit this step. This promotes unnecessary computation and increases the program's execution time. Therefore, we must utilize the fact that we aren't changing the vector's size by modifying the code slightly. We can do that by storing the size in a variable or using iterators, as shown below.
Eliminating Redundant Memory References
In the control path for executing a machine code, memory accesses are done using load and store instructions which are the most time-taking. They are often the sole bottlenecks that cause the program to take many more CPU cycles to execute than it should. That's why it's crucial to store frequently used values and expressions in variables so they can easily be accessed through CPU registers instead of from the cache, RAM, or secondary memory. Let's take an example where we once again find the sum of a vector and store it at a location in the main memory. We could do this by repeatedly accessing that location and incrementing its value like below.
In this example, we reference the location of 'sum_vector' 'N+1' times. That is extremely expensive, especially if 'N' is of a high order. We could alternatively limit the number of references to just two by modifying our approach by using variables stored in CPU registers, as shown in the subsequent code snippet.
Decreasing Instruction Interdependency and Utilizing ILP
In an ideal scenario, pipelining allows us to reduce the average cycles per instruction to about 1, but unfortunately, that rarely even comes close to happening. Consider the illustration of pipelined instruction execution displayed below.
This execution, with three instructions completed in 7 CPU cycles, is possible only when the three instructions are entirely independent (and other assumptions like no memory referencing). Although compilers enforce specific strategies like data-forwarding and branch-prediction to work with scenarios when instructions are interdependent, stalls are inevitable at some point or the other, at least while working with large programs. A large number of stalls occurring periodically could drastically increase the number of CPU cycles.
Get Vikram Setty’s stories in your inbox
Join Medium for free to get updates from this writer.
It is essential to work around this bottleneck as much as possible by making code segments independent from one another. This goes hand in hand with parallel or concurrent computation. If you have multiple, independent code segments to execute, execute them simultaneously, whether you have multiple cores or not. Take note of the example shown below.
ILP refers to instruction level parallelism. It's the 'illusion' that multiple instructions are being executed simultaneously when they are being implemented in a pipelined manner. If the pipelining is almost optimal or stalls aren't frequent, the program displays a high level of ILP. As programmers, we have to do our part in ensuring that happens!
Exploiting Spatial & Temporal Locality
Spatial Locality is based on the premise that locations close to another location that has been accessed have a high probability of being used in the near future. For example, if I currently access a block from the main memory, there's a good chance I'd be exploring areas surrounding that block soon too.
Temporal locality is quite similar, except that it specifies a high probability of reusing the same block of accessed memory again in the near future.
Both concepts are intuitive and apply to many programming applications, especially loops, where we usually iterate over a range of memory locations (high potential to exploit spatial locality) or repeatedly perform an operation on the same set of memory locations (high potential to exploit temporal locality). It's essential to have a good understanding of these concepts and fully use them because memory access is a costly step during instruction execution. Optimizing code concerning loading and storing data can have high returns in efficiency.
To illustrate how we can exploit these patterns while programming, we can look at the code for matrix multiplication, a principle that uses three nested loops and runs in O(N³) time. We can do this in 6 ways, by interchanging the order of the nested loops. Each of them is shown below.
Though all of these six implementations are identical in correctness and time-complexity, they vary quite a bit with respect to the time required to access blocks of memory (i.e., rows of A, columns of B, and cells of C). Some of these six implementations utilize spatial and temporal locality better than others. To compare, let's assume a block size of 4 and a single cache level. If an element is accessed, its entire block containing four elements is brought from the main memory into the cache. An element in the cache takes less time to access. Thus whenever we access a new element from the main memory, we bring its entire block into the cache to exploit spatial and temporal locality. We get a hit when the element we're looking for is already in the cache and a miss when it's not in the cache, in which case the new block has to be brought from the main memory. We'll also assume' N' to be significantly high. In such a case, by just observing the program flow, we can note hit and miss ratios in each case.
From this calculation, it is evident that the last two methods (k-i-j & i-k-j) encounter the least amount of misses and thus provide a considerable advantage by saving lots of time when multiplying huge matrices. By using spatial and temporal locality better, these two methods have the memory locations we need to access in the cache most of the time. Many of us might turn to the first method to multiply matrices out of habit, but now knowing this, I hope you make it a practice to tweak your approach and account for spatial and temporal locality next time.
Optimization Blocker 1: Potential Memory Aliasing
Now that we've gone over all the methods we can adopt to ease the compiler's work and make the program more efficient; we'll now turn to two specific cases where the compiler can't do anything just because of the nature of the program. These are called optimization blockers. The first blocker we'll look at is potential memory aliasing.
Memory aliasing is a situation where a single memory location can be accessed through multiple symbolic names or variables. But how is this a problem? Look at the two codes shown below. They should be equivalent to each other, right?
If the two cases mean the same thing, the compiler could easily view the first case as the second if and when it encounters it. This would reduce the instruction count and thus the number of CPU cycles too. However, the two cases need not be equivalent if you look closely enough. If even one of 'y' or 'z' point to the same location, case 1 and case 2 give different results. The compiler doesn't know where each pointer points and thus can't make assumptions. Hence, the compiler can't do much with code segments like in the first case and runs into optimization blockers.
Optimization Blocker 2: Potential Procedure Call Side Effects
Procedure calls can sometimes be tricky to optimize as well. Like the previous optimization blocker, let's look at two supposedly equivalent cases.
Is there any possibility that the two cases could return different values this time? The answer is, once again, yes. Imagine the possibility of global variables that get incremented within f(). In that case, they would increment twice as many times in the first case compared to the second. Thus, once again, the compiler can't optimize case 1 by equating it to case 2 and runs into an optimization blocker.
Reach Out for More!
I hope you got a good understanding of the different techniques and blockers I discussed. I hope you start incorporating these principles while programming next time too!
If you have any questions or want to know about anything in more detail, don't hesitate to contact me via Linkedin. I've linked my profile below.
References
This blog is built on the principles mentioned in the book 'Computer Systems: A Programmer's Perspective,' written by Randal Bryant and David O'Hallaron. It also takes inspiration from the lecture slides of Warren Hunt and Bill Young from UT Austin.
Other references include:
- [Figure 1] https://notesformsc.org/algorithms-order-of-growth/
- [Figure 2] https://www.vectorstock.com/royalty-free-vector/compiler-concept-icon-software-development-vector-29166490
- [Figure 3] https://stackoverflow.com/questions/32887943/multithreading-and-multitasking-on-single-core-processor-vs-multicore-processor
- [Figure 4] https://en.algorithmica.org/hpc/pipelining/








