简体   繁体   中英

Bit Shifting in Cache Simulation

What is the formula for calculating the index and tag bits in

  1. Direct Mapped Cache
  2. Associative Cache
  3. Set Associative Cache

I am currently using this formula for Direct Mapped:

#define BLOCK_SHIFT 5;
#define CACHE_SIZE 4096;
int index = (address >> BLOCK_SHIFT) & (CACHE_SIZE-1);
/* in the line above we want the "middle bits" that say where the block goes */
long tag = address >> BLOCK_SHIFT; /* the high order bits are the tag */

Please tell me how many bits are shifted in Associative and Set Associative Cache..

So, I think the concrete answer to your question is "zero", but that's simply because you are asking the wrong question.

Right, so a cache with a given size X, that is directly mapped, will simply use the lower part [or some other part(s)] of the address to form the index into the cache. So index is a value between 0 and (chace-size-1). In other words, "address modulo size". Since sizes of caches are nearly always 2 n , we make use of the fact that both of these can be performed using simple bitwise "and" with (size-1) instead of using divide.

In your code, each cache entry (cache-line) holds a "BLOCK" of 32 bytes, so the address should be divided (shifted) down by the block-size. 2 5 = 32. This shift remains a constant for a constant cache-line size. Since there is no other shift in your example code, I presume you are misunderstanding what you should do.

In a set-associative cache, there are multiple sets of cache-lines that can be used for the same index. So instead of simply taking the lower part of the address as an index, we take a SMALLER part of the lower address. So, the index = address_of_block & (CACHE_SIZE-1) should become address_of_block & ((CACHE_SIZE-1) / ways . Since we are dealing with a 2 n number again, we can use the old "shift instead of divide" trick - x / y where y is 2 n can be done by x >> n .

So, now you just have to figure out what n is for your number of ways.

And of course, figure out how you determine which of the ways to use when replacing something in the cache, but that is certainly a completely different question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM