brett
brett

Reputation: 5639

how to find cpu cache size for a x86 processor

I want to find cpu cache size of L1 or L2 caches using x86 assembly language. I heard cpuid and MSR registers have system specific data. Can some one help me how can I get sizes please.

Upvotes: 3

Views: 2209

Answers (3)

Michael F
Michael F

Reputation: 40832

Here's a minimal example of how you'd go about finding it out using the CPUID instruction:

#include <stdio.h>
#include <limits.h>

#define cpuid(id) __asm__( "cpuid" : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) : "a"(id), "b"(0), "c"(0), "d"(0))
#define b(val, base, end) ((val << (__WORDSIZE-end-1)) >> (__WORDSIZE-end+base-1))

int main(int argc, char **argv)
{
        unsigned long eax, ebx, ecx, edx;

        cpuid(0);
        printf("identification: \"%.4s%.4s%.4s\"\n", (char *)&ebx, (char *)&edx, (char *)&ecx);

        printf("cpu information:\n");

        cpuid(1);
        printf(" family %ld model %ld stepping %ld efamily %ld emodel %ld\n",
                        b(eax, 8, 11), b(eax, 4, 7), b(eax, 0, 3), b(eax, 20, 27), b(eax, 16, 19));
        printf(" brand %ld cflush sz %ld*8 nproc %ld apicid %ld\n",
                        b(ebx, 0, 7), b(ebx, 8, 15), b(ebx, 16, 23), b(ebx, 24, 31));

        cpuid(0x80000006);
        printf("L1 cache size (per core): %ld KB\n", b(ecx, 16, 31));

        return(0);
}

Upvotes: 4

PhiS
PhiS

Reputation: 4650

As Soravux suggests, the CPUID intruction is what you'll want to look at. (You might want to have a look at CPUID in e.g. the Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 2A, here).

The functions you'll probably be most interested in are: CPUID.EAX=02h and/or CPUID.EAX=04h (depending on your exact needs). These functions provide quite a lot of output, so I won't go through any details here, but Intel's and AMD's manuals should contain all you need.

Upvotes: 0

Soravux
Soravux

Reputation: 9963

You can use the CPUID instruction. If you set the EAX register to certain values, you can get the informations you want in the EAX, EBX, ECX and EDX registers.

You can have more informations in this guide from AMD.

Upvotes: 1

Related Questions