Cache lines required to hold an array

Viewed 94

Consider an Array declared in C as double a[100]. How many 64 byte cache lines are required to hold the complete array?

1 Answers

Short Answer: 100 / 64 / 8 = 12.5 -> 13 cache lines.

More Information: here is the general calculation: Assume you have X elements of type A. Since this is an array you can assume continuous memory. Let size(A) be the size in bytes of one element of type A. Assuming size(A) <= 64B, the number of 64B cache lines needed to hold the array is (X / (64 / size(A))).

Explanation: You want to calculate the number of elements per cache line, which is (64 / size(A)). Then you want to know how many cache lines are required for holding X elements which is X divided by the number of elements per cache line. You might want to round the result up in order to avoid issues like "false cache sharing".

For your case: Size of double is 8B (couldn't find any case where it would be 2B like the comment on the question suggests). You can fit (64 / 8) = 8 elements on each cache line. So you'll need (100 / 8) = 12.5 cache lines to hold the entire array. Since most of the time you'll want to avoid "false cache sharing", this means you'll probably take the entire 13th cache line as well.

Note: this works well when the size of the element divides the cache line size with no reminder. It would also work on the general case but would result in some elements being written on two different cache lines. This is not idle in general as you'll have to sometime read two cache lines in order to read a single value, but as you're dealing with a continuous array, it is less of a big deal. If you do want to calculate for the general case without elements crossing cache lines simply use: (X / floor(64 / size(A))). E.g. if A was a long double over a 32b system size(A) would be 10B. In this case the first formula would give (100 / (64 / 10)) = 15.625, but without crossing cache lines you'll get (100 / floor(64 / 10)) = 100 / 6 = 16.6 - so one more cache line in total.

Related