CPU cache ဆိုတာ ဘာလဲ။

Published: (January 15, 2026 at 10:24 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

CPU Cache အကြောင်း အကျဉ်းချုပ်

Cache ကို မြန်မာလို ပြောရရင် “ခေတ္တယာယီနေရာ” လို့ ဆိုနိုင်ပါတယ်။ CPU မှာ L1, L2, L3 cache တွေရှိပြီး

  • L1 – Core တစ်ခုစီမှာ အလိုအလျောက် ပါ (အရွယ်အစား ≈ 32 KB)
  • L2 – Core တစ်ခုစီမှာ ပါ (အရွယ်အစား ≈ 256 KB)
  • L3 – အားလုံးအတွက် shared cache (အရွယ်အစား အများကြီး)

CPU သည် instruction တစ်ခုကို ဖတ်လိုက်သောအခါ အရင်ဆုံး L1 cache မှာ ရှာမယ်။ L1 မှာ အချက်အလက်တွေ ရှိရင် 3‑5 cycles အတွင်း ယူနိုင်ပြီး အလွန်မြန်ပါတယ်။ L1 မှာ မတွေ့ရင် L2 (10‑15 cycles) ကို၊ အဲဒါမှ မတွေ့ရင် L3 (50‑100 cycles) ကို ဆက်ရှာသွားပါတယ်။

Cache‑friendly code

C++ မှာ cache‑friendly ဖြစ်တဲ့ အခြေခံနည်းက row‑major access ဖြစ်ပါတယ်။

မဟုတ်တဲ့ (cache‑unfriendly) ကုဒ်

for (int col = 0; col < N; ++col) {
    for (int row = 0; row < N; ++row) {
        sum += matrix[row][col];
    }
}

Cache‑efficient (row‑major) ကုဒ်

for (int row = 0; row < N; ++row) {
    for (int col = 0; col < N; ++col) {
        sum += matrix[row][col];
    }
}

Row‑major access ဘာကြောင့် cache‑friendly?

2‑dimensional array ဥပမာ

int matrix[4][4] = {
    { 1,  2,  3,  4},  // row 0
    { 5,  6,  7,  8},  // row 1
    { 9, 10, 11, 12},  // row 2
    {13, 14, 15, 16}   // row 3
};

Memory layout (address)

ElementValueAddress
matrix[0][0]10x1000
matrix[0][1]20x1004
matrix[0][2]30x1008
matrix[0][3]40x100C
matrix[1][0]50x1010
matrix[1][1]60x1014
matrix[1][2]70x1018
matrix[1][3]80x101C
matrix[2][0]90x1020
matrix[2][1]100x1024
matrix[2][2]110x1028
matrix[2][3]120x102C
matrix[3][0]130x1030
matrix[3][1]140x1034
matrix[3][2]150x1038
matrix[3][3]160x103C

C++ မှာ row‑major အစီအစဉ်ဖြစ်တဲ့အတွက် အတန်း (row) တစ်ခုအတွင်း အကွာအဝေး 4 bytes (int) တိုးတက်ပြီး ဆက်တိုက် memory address တွေကို လိုက်လံသုံးပါတယ်။

CPU သည် matrix[0][0] ကို မူလတန်းတစ်ခုအနေဖြင့် လိုက်လံရှာပြီး မတွေ့ရင် 64 byte အရွယ်အစား cache line တစ်ခုကို memory ထဲကယူသွားပါတယ်။ အဲဒီ cache line ထဲမှာ matrix[0][0]matrix[0][1]matrix[0][2] … အစရှိသဖြင့် အတန်းတစ်ခုလုံး ပါဝင်နေပါတယ်။ ထို့ကြောင့် loop အတွင်း matrix[0][1]matrix[0][2] စသည့် အချက်အလက်တွေကို CPU သည် cache မှတစ်ဆင့် 4 bytes တိုးတက်ပြီး အလွယ်တကူ ဖတ်နိုင်သဖြင့် လုပ်ဆောင်ချက် အလွန်မြန်သွားပါသည်။

Back to Blog

Related posts

Read more »

Rapg: TUI-based Secret Manager

We've all been there. You join a new project, and the first thing you hear is: > 'Check the pinned message in Slack for the .env file.' Or you have several .env...

HackPrix Season 1 Recap

Overview Introducing HackPrix, an initiative by the HackPrix community—a space where innovation meets expertise and ideas are given room to bloom. HackPrix Sea...

Build Quincy's Job Tips Page

Introduction This morning I tackled the next workshop in the Responsive Web Design certification on freeCodeCamp: building a job tips page. The workshop provid...