Computer Science and IT‹›⌂ 0:00 studied

Module 3 · 14 min read · Free chapter

Memory hierarchy and cache

In short

Caches work because of temporal and spatial locality. The address splits into tag, index and offset, where offset is log₂ of the block size and index is log₂ of the lines or sets. Hierarchical access time is Tc + (1 − h)Tm, and write-back uses a dirty bit.

See it in 3DCache and memory hierarchy: from the motherboard to the L1 cache. Turn it, cut it open, or just press Watch.
What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: the masala box

Think of a home kitchen. The salt, haldi and jeera you use every day sit in a small masala box right next to the stove. Bigger stocks of dal and rice are in the store room, and anything you run out of comes from the market.

You keep the box small because counter space is precious, and you can grab from it in a second. A trip to the store room takes a minute, and a trip to the market takes an hour. The kitchen still feels fast, because almost everything you reach for is already in the box.

A computer arranges its memory the same way. A tiny, very fast cache sits next to the processor, a larger and slower main memory sits further away, and a huge but slow disk holds everything else. This chapter shows why this works and how the cache decides what to keep.

Why it matters. A processor can do an addition in well under a nanosecond, but a trip to main memory takes many times longer. Without a cache, the processor would spend most of its time waiting, so cache design decides real speed.

Locality and the memory hierarchy

A cache works only because programs are predictable in a special way, called locality of reference. Temporal locality means that a word used now is likely to be used again soon, like a loop counter. Spatial locality means that words near it are likely to be used soon, like the next element of an array or the next instruction.

So when the processor needs a word that is not in the cache, the cache fetches a whole block (also called a line) of nearby words. Spatial locality makes the rest of the block useful, and temporal locality makes it worth keeping for a while.

The levels form a hierarchy. At the top are registers, then one or more levels of cache made of SRAM, then main memory made of DRAM, and at the bottom SSDs and hard disks. Going down, each level is bigger and cheaper per bit but slower.

SRAM keeps each bit in a flip-flop of several transistors, so it is fast and needs no refresh, but it is costly and takes space. DRAM keeps each bit as charge on a tiny capacitor, so it is dense and cheap, but the charge leaks and must be refreshed again and again.

Why it matters. The hierarchy gives the illusion of a memory as large as the disk and almost as fast as the cache. Exams ask why caches work, which locality a given loop shows, and why cache uses SRAM while main memory uses DRAM.

Hit ratio and average access time

When the word is found in the cache it is a hit; otherwise it is a miss. The hit ratio hh is hits divided by total accesses, and 1−h1 - h is the miss ratio. The average access time depends on how the cache and memory are searched.

In hierarchical (look-through) access the cache is checked first, and memory is accessed only after a miss. Every access pays the cache time, and misses also pay the memory time. In simultaneous (look-aside) access both start together, and a hit simply cancels the memory access.

Hierarchical: Tavg=Tc+(1−h)TmSimultaneous: Tavg=hTc+(1−h)Tm\text{Hierarchical: } T_{\mathit{avg}} = T_c + (1 - h)T_m \qquad \text{Simultaneous: } T_{\mathit{avg}} = hT_c + (1 - h)T_m

Worked example. Let TcT_c = 2 ns, TmT_m = 50 ns and h=0.95h = 0.95. Hierarchical access gives 2+0.05×50=4.52 + 0.05 \times 50 = 4.5 ns, and simultaneous access gives 0.95×2+0.05×50=4.40.95 \times 2 + 0.05 \times 50 = 4.4 ns. Without any cache every access would take 50 ns, so the cache gives a speed-up of about 504.5≈11\dfrac{50}{4.5} \approx 11.

The same formula can be turned around. To keep the hierarchical average at 3 ns with these times, we need 2+(1−h)×50=32 + (1 - h) \times 50 = 3, so 1−h=0.021 - h = 0.02 and the hit ratio must be at least 0.98.

Why it matters. Small changes in hit ratio make large changes in speed, because each miss is so costly. A rise from 95 to 98 percent cuts the average here from 4.5 to 3 ns.

Cache mapping and tag-index-offset numericals

Main memory is divided into blocks of the same size as cache lines, and mapping decides where a block may go. In a direct-mapped cache each block has exactly one line, given by block number mod number of lines. In a fully associative cache a block may go into any line, and in a k-way set-associative cache the lines are grouped into sets of kk, and a block may go into any line of one set, given by block number mod number of sets.

To find a block, the address is split into three fields. The offset picks a byte inside the block, the index picks a line or a set, and the tag is stored with the line to tell which block is there now.

offset=log⁡2(block size),index=log⁡2(lines or sets),tag=address bits−index−offset\text{offset} = \log_2(\text{block size}), \qquad \text{index} = \log_2(\text{lines or sets}), \qquad \text{tag} = \text{address bits} - \text{index} - \text{offset}

Worked example. A 64 KB cache has 32-byte blocks, and addresses are 32 bits with byte addressing. There are 6553632=2048\dfrac{65536}{32} = 2048 lines, so the offset is 5 bits.

Mapping Index bits Tag bits Comparators
Direct mapped, 2048 lines 11 32−11−5=1632 - 11 - 5 = 16 1
2-way, 1024 sets 10 17 2
4-way, 512 sets 9 18 4
Fully associative 0 27 2048

Each line also stores its tag in a tag directory, with a valid bit and, for write-back, a dirty bit. For the direct-mapped case with one valid bit, the tag directory holds 2048×(16+1)=348162048 \times (16 + 1) = 34816 bits.

To place a block, divide. Block 4100 of memory goes to line 4100 mod 2048=44100 \bmod 2048 = 4 in the direct-mapped cache, and to set 4100 mod 1024=44100 \bmod 1024 = 4 in the 2-way cache.

Why it matters. Tag-index-offset splits appear in nearly every GATE paper. Doubling the associativity removes one index bit and adds one tag bit, which is a quick check on any answer.

Misses, associativity and replacement

Misses come in three kinds, often called the three Cs. Compulsory misses happen on the very first access to a block, capacity misses happen because the cache cannot hold all the blocks a program is using, and conflict misses happen when several blocks fight over the same line or set even though other lines are free.

Worked example. A cache has 4 lines and the processor asks for blocks 0, 4, 0, 8, 4, 1, 5, 1. In a direct-mapped cache, blocks 0, 4 and 8 all map to line 0 and blocks 1 and 5 to line 1, so every one of the 8 accesses misses. In a 2-way set-associative cache with 2 sets and LRU replacement, the third access (block 0) and the last access (block 1) hit, giving 2 hits out of 8.

When a set is full, a replacement policy picks the victim. LRU removes the block unused for the longest time, which suits temporal locality, while FIFO removes the block that came in first and random picks any block. The optimal policy removes the block whose next use is farthest away; it needs knowledge of the future, so it serves only as a benchmark.

Higher associativity cuts conflict misses, but each lookup must compare more tags at once, which costs hardware and slightly slows every hit. That is why real caches usually stop at 4 to 16 ways.

Why it matters. GATE often gives an access trace and asks for hits or misses under a mapping and a policy. Draw one column per line or set and fill it access by access, marking each hit.

Write policies and multilevel caches

Reads are easy, but a write must keep the cache and memory consistent. Write-through writes every store to both the cache and main memory, usually through a small write buffer so the processor need not wait. It is simple and memory is always up to date, but it creates heavy memory traffic.

Write-back writes only to the cache and sets a dirty bit on the line. The line is written to memory only when it is evicted, so repeated writes to the same word cost one memory write. The price is a slower miss when the victim is dirty, because it must be written out before the new block comes in.

On a write miss there is a second choice. Write-allocate brings the block into the cache and then writes it, which pairs naturally with write-back, while no-write-allocate writes straight to memory, which pairs with write-through.

Modern processors use two or three levels of cache. A small, very fast L1 catches most accesses, and a bigger L2 catches most of L1's misses before they reach memory.

Tavg=TL1+m1(TL2+m2Tm)T_{\mathit{avg}} = T_{L1} + m_1(T_{L2} + m_2 T_m)

Here m1m_1 is the L1 miss rate and m2m_2 is the local miss rate of L2, that is, its misses divided by the accesses that reach it.

Worked example. Let TL1T_{L1} = 1 ns with m1=0.1m_1 = 0.1, TL2T_{L2} = 10 ns with m2=0.2m_2 = 0.2, and TmT_m = 100 ns. Then Tavg=1+0.1×(10+0.2×100)=1+0.1×30=4T_{\mathit{avg}} = 1 + 0.1 \times (10 + 0.2 \times 100) = 1 + 0.1 \times 30 = 4 ns. The global L2 miss rate is 0.1×0.2=0.020.1 \times 0.2 = 0.02, so only 2 percent of all accesses reach main memory.

Why it matters. Write policy changes memory traffic and miss cost, so it appears in both MCQs and descriptive answers. Multilevel numericals are common in GATE, and the usual mistake is to use the global miss rate where the local one belongs.

Main memory interleaving and secondary storage

A DRAM module needs time to recover after each access, so reading a block word by word from one module is slow. Interleaving spreads memory over MM modules that can work in parallel. In low-order interleaving, address aa lives in module a mod Ma \bmod M, so the words of a block sit in different modules and can be read together.

Worked example. A cache block has 4 words, each module takes 40 ns per access, and the bus takes 10 ns to move one word. From a single module the block needs 4×(40+10)=2004 \times (40 + 10) = 200 ns. With 4-way low-order interleaving all four modules start together, so the block needs 40+4×10=8040 + 4 \times 10 = 80 ns.

In high-order interleaving the top address bits choose the module, so consecutive addresses stay in one module. That does not speed up a block fetch, but it lets different programs or devices use different modules at once.

Below main memory lies secondary storage, which keeps data when the power is off. A hard disk has spinning platters divided into tracks and sectors, and a head on a moving arm reads them. Its access time is seek time plus rotational latency plus transfer time, as detailed in disk structure and scheduling.

Worked example. At 7,200 rpm one rotation takes 607200\dfrac{60}{7200} s, which is 8.33 ms. On average the wanted sector is half a rotation away, so the average rotational latency is 4.17 ms. A solid-state drive (SSD) stores data in flash chips with no moving parts, so it has no seek or rotational delay.

Why it matters. Interleaving explains how memory keeps up with fast block fetches, and disk timing explains why a page fault costs millions of processor cycles. Both appear as short numericals in GATE and ISRO papers.

Descriptive lens: how written papers ask this

Written papers for engineering services, IT officer posts and state Assistant Programmer exams ask about this topic in four ways:

  1. Explain the memory hierarchy and the principle of locality that makes it work.
  2. Compare direct, fully associative and set-associative mapping with a diagram of the address split.
  3. Calculate tag, index and offset bits, tag directory size and average access time for given data.
  4. Compare write-through and write-back, and discuss replacement policies.

Practice questions (our own, not previous-year questions).

  1. Explain temporal and spatial locality with one program example each, and show how they justify a cache with multi-word blocks. (10 marks)
  2. A 128 KB, 4-way set-associative cache uses 64-byte blocks and 32-bit byte addresses. Find the tag, set and offset bits and the tag directory size with one valid and one dirty bit per line. (10 marks)
  3. Compare write-through and write-back policies, and explain write-allocate with an example of a write miss. (15 marks)

Answer plan for question 2.

  • Find the number of lines as 13107264=2048\dfrac{131072}{64} = 2048 and the number of sets as 20484=512\dfrac{2048}{4} = 512.
  • Give the offset as log⁡264=6\log_2 64 = 6 bits and the set index as log⁡2512=9\log_2 512 = 9 bits.
  • Find the tag as 32−9−6=1732 - 9 - 6 = 17 bits.
  • Add one valid and one dirty bit to get 19 bits per line.
  • Multiply to get the tag directory size as 2048×19=389122048 \times 19 = 38912 bits.
  • Note that four comparators are needed, one for each way in the set.

Quick revision

  • Temporal locality means reuse soon, and spatial locality means neighbours soon.
  • Going down the hierarchy, size rises, cost per bit falls and speed falls, and caches use SRAM while main memory uses DRAM.
  • Hierarchical access gives Tc+(1−h)TmT_c + (1 - h)T_m, and simultaneous access gives hTc+(1−h)TmhT_c + (1 - h)T_m.
  • Offset is log⁡2\log_2 of the block size, index is log⁡2\log_2 of lines or sets, and tag is the rest.
  • Doubling associativity removes one index bit and adds one tag bit.
  • Misses are compulsory, capacity or conflict, and LRU evicts the least recently used block.
  • Write-back uses a dirty bit and writes on eviction, while write-through writes memory every time.
  • Two-level access time is TL1+m1(TL2+m2Tm)T_{L1} + m_1(T_{L2} + m_2 T_m) with the local L2 miss rate.
  • Low-order interleaving puts address aa in module a mod Ma \bmod M.
  • Disk access is seek plus rotational latency plus transfer, and average rotational latency is half a rotation.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 14 answered

  1. Accessing the elements of an array one after another mainly shows:

  2. Cache memory is usually built from:

  3. Which memory must be refreshed periodically?

  4. With TcT_c = 2 ns, TmT_m = 50 ns and hit ratio 0.95, the average access time for hierarchical access is:

  5. A 64 KB direct-mapped cache has 32-byte blocks and 32-bit byte addresses. The tag has:

  6. The same 64 KB cache made 2-way set-associative has a set index of:

  7. In a direct-mapped cache with 2048 lines, memory block 4100 maps to line:

  8. A direct-mapped cache has 2048 lines with a 16-bit tag and one valid bit per line. The tag directory size is:

  9. Misses caused because several blocks map to the same line while other lines are free are:

  10. Which cache organisation needs no replacement policy?

  11. The dirty bit is needed in which write policy?

  12. L1 takes 1 ns with miss rate 0.1, L2 takes 10 ns with local miss rate 0.2, and memory takes 100 ns. The average access time is:

  13. In 4-way low-order interleaving, address 13 lies in module:

  14. A disk spins at 7,200 rpm. Its average rotational latency is about:

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

How are tag, index and offset bits found?

Offset is log₂ of the block size, index is log₂ of the number of lines (or sets), and the tag is the remaining address bits.

What is the average memory access time with a cache?

For hierarchical access it is Tc + (1 − h)Tm, and for simultaneous access it is hTc + (1 − h)Tm.

What is the difference between write-through and write-back?

Write-through writes both cache and memory every time, while write-back writes only the cache and updates memory when a dirty line is evicted.

What is average rotational latency of a disk?

It is half of one rotation time, so a 7,200 rpm disk has about 4.17 ms.

More in this module: Computer organisation and architecture

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Computer Organization and Architecture (IIT Madras, 106106166): memory hierarchy and cache memory