Cache In a Multi-Core Computer

In my previous article (link) I discussed the use of cache and some practices that can provide increased performance while also teaching you what cache is. I also stated that cache in a multicore environment is a whole other topic so I’ve written this article to cover the different considerations that come along with Multicore Programming.

Why does it matter if we’re using two cores?

Cache comes in levels, typically 3 each with their own group of cores that can access it, L1 Cache is only visible to a single core with each core having it’s own private cache and is the fastest of all caches. L2 Cache is usually visible to a group of cores, for instance, the AMD 8150 shares L2 Cache between two cores and finally there’s L3 Cache that is accessible to all cores and is the slowest of caches, but still much faster in comparison to RAM.

Now that we know that there are different banks of cache for each core, what happens when two cores are accessing the same memory? If there was no system in place then both cores would cache the memory, then let’s say one core wrote to that memory, This would be visible in memory, although the other core would still have its cache of the old value. To solve this when a core writes to its cached memory; Any other core that stores that cache line will be removed or updated, which is where our problem comes into play.

Let’s say you have 2 Integers on a single cache line and each core was writing to an integer each that are next to each other in an array, although they’re not the same variables and it won’t cause any unexpected results because they’re on the same cache line. Every time one core writes to that memory, the other core loses its cache. This is referred to as False Sharing and there’s a simple solution to this, the hardest part is determining if you’re having this problem.

False Sharing

False Sharing can hinder the performance for any program. For this example I’ll go through the optimizations I did on a single producer single consumer queue and provide a few steps to solving most of your False Sharing problems. To test the queue I have two threads, one writing integers from 0 to 1 million and another reading them and checking if they’re all in order. The queue doesn’t undergo any resizing and is allocated with enough capacity for 1 million objects.

<code>
template<typedef T>
class alignas(64) Queue{
T* data_;
size_t push_position_;
size_t pop_position_;
std::atomic<size_t> size_;
size_t capacity_;
};
</code>

The problem with this code is that all the variables are packed together with no spacing together, the whole structure would fit on up to two cache lines. This is perfect if we’re in a single core environment, although separate cores access pop_position and push_position therefore there’s high contention between these cache lines in a multicore Environment.

I break the problem down into a shared read section; shared write section and one section for each thread. A section may be larger than a single cache line and may require two cache lines to implement, it’s for this reason I call them a section. Our first step would be to determine what memory belongs to what section. With data_ and capacity_ both being shared, but rarely written to, they therefore belong to the shared read cache line, size_ is the only variable that is a shared write and push and pop both belong to their own cache line as each thread uses one each. In this example that leaves us with 4 cache lines. This leaves us with

<code>
template<typedef T>
class alignas(64) Queue{
// Producers C-Line
size_t push_position_;
char pad_p[64 – sizeof(size_t)];
// Consumers C-Line
size_t pop_position_;
char pad_c[64 – sizeof(size_t)];
// Shared Read C-Line
T* data_;
size_t capacity_;
char pad_sr[64 – sizeof(size_t) – sizeof(T*)];
// Shared Write C-Line
std::atomic<size_t> size_;
char pad_sw[64 – sizeof(std::atomic<size_t>)];
};
</code>

Notice that the alignas(n) this is a new keyword added in C++14. The keyword ensures that the structure is aligned to a multiple of n bytes in memory and therefore allows us to assume that our first variable will be placed at the start of a cache line, which is vital for our separation.

Before accounting for False sharing, to push and pop 1 million Integers it took 60ms, but after accounting for False Sharing it’s been reduced to 34ms on an Intel Core I5 3210M @ 2.5Ghz. The majority of the time comes from the atomic access, which we use to check to see if there’s room to push and anything to pop. You could potentially optimize the atomic access out of most of the pushes by remembering how many objects can be pushed and popped until your next size check, this way we can lower the atomic access and dramatically improve performance again.

https://gist.github.com/Joshhua5/2ce996a08effe44f2f0f

While on the same subject of False Sharing, another example would occur when storing data within an array and having a number of threads access that array. Let us think about a pool of threads which keep count how much work they’ve done and store it in an array. We need access to these variables to check how much work’s been done while running.

<code>
int work_done[n];
</code>

An easy mistake to make, but would result in a plethora of cache misses. As each core goes to increment it’s work_done it would invalidate the other cores cache. A solution to this would be to turn the array into an array of pointers to store a pointer to a local variable inside the thread, this would require that we pass a pointer to work_done so we can populate that pointer with the address of the local variable. From a synthetic test where the worker thread is only iterating on work_done, we can see over 5 seconds of iteration across 4 cores we get a result of ~890M iterations per core while once we’d accounted for False Sharing and utilized local variables we get a result of ~1.8B iterations per core which are a ~2x improvement on the I5 3210M @ 2.5Ghz. The same test on an AMD 8150 @ 4.2Ghz reached 44M iterations with False Sharing, while without we reached 2.3B iterations which are a shocking ~52x improvement in speed, I had to double check this result because it’s left me in disbelief**! In this case, we use a local variable instead of padding between all the variables to save space, but both would work equally as well.

https://gist.github.com/Joshhua5/5b6e9e50b3318244656b

Volatile Data

Another problem isn’t exactly cache related, although it’s still important, as a register is the fastest memory available. A register is a tiny piece of memory that’s specific to each core and can be accessed in typically 1 cycle. The key difference between a register and cache is that a register is a local memory and isn’t supposed to be a fast clone of what’s in RAM like the cache is. A program quite often will copy a value from RAM into a register, work on it there and then write back out to RAM once it’s finished. In a single threaded program this is fine, but in the situation where you have two cores editing the same integer, both may take a local copy of the integer, edit it and then write back. Each core would be writing over each other’s result because they never saw the other cores work. C++ has a solution to this assuming that you’ve prevented both cores from reading and writing at the exact same time. The volatile keyword tells the compiler to never store this value in a register so the other cores work is always visible, but now I’m getting into Multicore Programming and not cache for multicore programs.

<code>
volatile int x = 0;
</code>

Summary
Only use an Atomic when necessary, check if a volatile will meet your needs first.
Keep classes with multicore access segmented by cache lines to eliminate False Sharing
Local variables are preferred over sharing data outside of the thread

Conclusion

False Sharing can be a problematic side effect of multicore programming which should be a consideration whenever two cores use data in proximity to one another. From these tests on an Intel 3210M we can see that by eliminating False Sharing we receive a ~2x performance boost, obviously, this would differ on different hardware. A tool that can be useful with multicore programming is volatile variable, although these have their own issues when two cores write the variable, they can still be a useful replacement to an atomic in read-only situations.
* AMD 8150 is tested on Windows 8.1 with Visual Studio 2013 and Intel 3210M is tested on OSX 10.10 LLVM 6.1.0.

** After seeing such a large difference, I went looking for a cause to such dramatic performance loss; I found that the L3 cache on the Bulldozer architecture is broken into 2MB per module (2 cores) that cannot be accessed by other modules [1]. Sharing would result in a cache miss all the way to RAM, while the I5 3210M shares it L3 Cache between all cores and would only need to go to the L3 cache in the case of a cache miss. This wouldn’t be a problem if the operating system had placed the threads onto the two cores in a module. I kept running the tests with 2 threads until the result went from 44M to 1.2B per thread, assuming that in these cases the threads were placed on the same module and therefore shared L3 cache. This is a perfect example of the importance of testing your software on different hardware.
[1] isscc.org/doc/2011/isscc2011.advanceprogrambooklet_abstracts.pdf pg. 40

Cache And How To Work For It

Why Cache Matters 

Simply put, Cache is a small amount of memory located on your CPU that is used to reduce latencies to main memory (RAM). We have no control over the cache, but programming and storing data in a cache-friendly manner is imperative to performance improvements and, in turn, a reduction in power consumption. Without realising it, you may have already used a form of Cache before when reading files from an HDD where you have loaded the file into RAM and then manipulated it there before writing back the changes, you’ve cached the file on the RAM. Although this example is slightly different and technically a buffer, the similarities are present.

How Cache Works

When your CPU requests a piece of memory it’ll go out to the RAM to fetch it. During that time the CPU is waiting while the request goes through the Memory Controller, on the CPU chip to the RAM to be served and returned. This is a waste of possible compute time and therefore a reduction in power efficiency. Cache sits between this line of communication and listens in on the requests to RAM; if it has the memory already it’ll stop the request and respond with what it has, this is referred to a Cache Hit and if it’s unable to serve the request because it doesn’t have the requested memory then it’s a Cache Miss.

There are systems in place to assure that when writing to memory, both the Cache and memory are updated, but I’ll save those for another article, as they are more important when working with a multithreaded application.

The part that we can assist

The Cache is always trying to guess what memory you’ll need to have before you request it, this prediction is called Cache Prefetching. This is why when working on an array it’s best to go through in sequential order instead of randomly jumping through, as the Cache Prefetcher will be able to guess what you’re using and have it ready before you need it. Cache loads things in groups of 64 bytes. The size is CPU-dependant and can be checked under your CPU’s specification under Cache Line size, although it’s typically 64 bytes. This means that if you have an array of integers and you grab 1 of those integers, the cache has also grabbed the Cache Line that it sits on. Grabbing the next integer stored next to it will be a Cache Hit and subsequently extremely fast. The alignment of the Cache Line will always be a multiple of the Cache Line’s size, meaning that if you fetch memory at 0x00 (0) then what will be cached is everything between 0x00 (0) and 0x40 (64) and if you fetch something at 0x4F (79) then you’ll get everything between 0x40 (64) and 0x80 (128).

Use Case

Arrays store their data sequentially, so they’re ideal for accessing in a cache-friendly way. In this example we access data going across the row before going to the next row and then in the second loop, we go across the column first and then move to the next column. Each dimension in the array contains 10,000 integers.

 [C++]

for (unsigned x = 0; x < ARRAY_SIZE; ++x)

for (unsigned y = 0; y < ARRAY_SIZE; ++y)

  total += array_[ y ][ x ];

for (unsigned x = 0; x < ARRAY_SIZE; ++x)

for (unsigned y = 0; y < ARRAY_SIZE; ++y)

  total += array_[ x ][ y ];

[/C++]

The only difference between these loops is the <tt>array_[x][y]</tt> and <tt>[y][x]</tt>, but the results between the two are extreme. On my AMD 8150, the first loop finished in 1,501ms while the second only took 281ms which is a ~5x speed increase! Simply because of the Prefetcher friendly access, although the first loop may look sequential, it’s actually extremely fragmented in its accesses. A 2D array stores its data in one large block with each row next to each other and after each row, it is the next row (Row-Major order). In the diagram below we have the access patterns of the two loops showing the order of their access and the values returned. The first loop accesses its data in a predictable way, but not a way that the Prefetcher is able to prefetch for. While the second loop accesses its memory sequentially which allows the CPU to prefetch.

    

Example source: https://gist.github.com/Joshhua5/c0fe80d67d3990c528e7

<code>

(Access) 1 2 3 4 5 6 7 8 9

(Loop 1) 1 4 7 2 5 8 3 6 9

(Loop 2) 1 2 3 4 5 6 7 8 9

</code>

   

One more example of an optimisation is the layout of a class, assuming that your compiler doesn’t optimise this for you.     

<code>

struct Foo{

bool value1;

char data[64];

bool value2;

}

</code>

Let’s say we want to check <tt>value1</tt> and <tt>value2</tt> before accessing any data inside the array. Let’s also assume that <tt>Foo</tt> is stored at 0x00 for simplicity. When we access <tt>value1</tt>, we’ll have a Cache Miss as it’s our first time accessing this piece of memory, but now we’ve got that line stored for us. We then check <tt>value2</tt>, which will also result in a Cache Miss, because data has polluted our Cache Line and pushed <tt>value2</tt> into the next line meaning we now have to wait twice. An alternative would be to store <tt>value1</tt> and <tt>value2</tt> next to each other so that we only have the first Cache Miss and a Cache Hit for the second. Assuming we don’t access <tt>data[62]</tt> and upwards then we won’t have to deal with another Cache Miss. Optimally we could store <tt>value1</tt> and <tt>value2</tt> in the same byte because we only need one bit to store a Boolean and could technically fit eight Booleans into a single byte. If we performed this optimisation and used bitwise shifting to access each byte we could squeeze another byte of the array into out cache line.

Example source: https://gist.github.com/Joshhua5/83da475070174f309ff2

From this, on the AMD 8150 we received 47ms for the first loop and 31ms for the second loop which is a 1.5x performance increase. Notice that we have to times the array access by * 2 to break up sequential access because there would be no performance difference between the two loops. If we always fetch 64 bytes then we’re bound to fetch more than needed for value2 and therefore cache the next object in the array unintentionally. Another interesting behaviour which shows the function of the prefetcher is if we accessed the array sequentially so the CPU could prefetch it would only take 15ms to go through the entire array instead of 31ms to go through half the array ‘randomly’.

Summary 

  • Optimally, you want objects to be as small as possible to fit as many in a Cache Line as possible. You can fit two shorts in an integer and therefore 16 integers in a cache line or 32 if you use shorts.
  • Consider a pointer, first to fetch that pointer from memory is a Cache Miss and then fetching that object is a second Cache Miss is a worst case scenario.
  • Keep objects smaller than the Cache Line or divisible by it to prevent a single object spreading over two Cache Lines.
  • C++14 added the <tt>alignas</tt> keyword that will make sure that these objects are aligned in memory to the value passed which can be beneficial in stopping an object being placed in two Cache Lines.

Conclusion

Cache is more important than ever with the extreme speeds of CPU and relatively slow RAM, great speed improvements or power efficiency can be observed from utilising it correctly which is always welcome in the world of game creation.

For a deeper look into how to you can change your design practices for better Cache utilisation, I’d highly recommend watching this video: https://vimeo.com/97337258 – Scott Meyers – Norwegian Developers Conference