How can I programmatically measure (not query the OS) the size and order of associativity of L1 and L2 caches (data caches)?
Assumptions about system:
There are no assumptions about OS (it can be Linux, Windows, or something else), and we can't use POSIX queries.
Language is C, and compiler optimizations may be disabled.
Modern systems often use at least two levels of caches, as shown in Figure 8.16. The first-level (L1) cache is small enough to provide a one- or two-cycle access time. The second-level (L2) cache is also built from SRAM but is larger, and therefore slower, than the L1 cache.
Cache is graded as Level 1 (L1), Level 2 (L2) and Level 3 (L3): L1 is usually part of the CPU chip itself and is both the smallest and the fastest to access. Its size is often restricted to between 8 KB and 64 KB. L2 and L3 caches are bigger than L1.
If the size of L1 was the same or bigger than the size of L2, then L2 could not accomodate for more cache lines than L1, and would not be able to deal with L1 cache misses. From the design/cost perspective, L1 cache is bound to the processor and faster than L2.
I think all you need to do is repeatedly access memory in ever-increasing chunks (to determine cache size), and I think you can vary the strides to determine associativity.
So you would start out trying to access very short segments of memory and keep doubling the size until access slows down. Every time access slows down you've determined the size of another level of cache.
Here is the code from ATLAS. It is for L1 cache size
ATLAS/tune/sysinfo/L1CacheSize.c
(https://github.com/vtjnash/atlas-3.10.0/blob/master/tune/sysinfo/L1CacheSize.c)
int GetL1Size(int MaxSize, double tol)
{
int L1Size, tmp, correct=1;
fprintf(stderr, "\n Calculating L1 cache size:\n");
but it is only l1 cache and only size of it, not the way-count.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With