All platforms welcome, please specify the platform for your answer.
A similar question: How to programmatically get the CPU cache page size in C++?
All platforms welcome, please specify the platform for your answer.
A similar question: How to programmatically get the CPU cache page size in C++?
On Linux (with a reasonably recent kernel), you can get this information out of /sys:
/sys/devices/system/cpu/cpu0/cache/
This directory has a subdirectory for each level of cache. Each of those directories contains the following files:
coherency_line_size
level
number_of_sets
physical_line_partition
shared_cpu_list
shared_cpu_map
size
type
ways_of_associativity
This gives you more information about the cache then you'd ever hope to know, including the cacheline size (coherency_line_size) as well as what CPUs share this cache. This is very useful if you are doing multithreaded programming with shared data (you'll get better results if the threads sharing data are also sharing a cache).
On x86, you can use the CPUID instruction with function 2 to determine various properties of the cache and the TLB. Parsing the output of function 2 is somewhat complicated, so I'll refer you to section 3.1.3 of the Intel Processor Identification and the CPUID Instruction (PDF).
To get this data from C/C++ code, you'll need to use inline assembly, compiler intrinsics, or call an external assembly function to perform the CPUID instruction.
If you're using SDL2 you can use this function:
int SDL_GetCPUCacheLineSize(void);
Which returns the size of the L1 cache line size, in bytes.
In my x86_64 machine, running this code snippet:
printf("CacheLineSize = %d",SDL_GetCPUCacheLineSize());
Produces CacheLineSize = 64
I know I'm a little late, but just adding information for future visitors. The SDL documentation currently says the number returned is in KB, but it is actually in bytes.
On the Windows platform:
from http://blogs.msdn.com/oldnewthing/archive/2009/12/08/9933836.aspx
The GetLogicalProcessorInformation function will give you characteristics of the logical processors in use by the system. You can walk the SYSTEM_LOGICAL_PROCESSOR_INFORMATION returned by the function looking for entries of type RelationCache. Each such entry contains a ProcessorMask which tells you which processor(s) the entry applies to, and in the CACHE_DESCRIPTOR, it tells you what type of cache is being described and how big the cache line is for that cache.
You can use std::hardware_destructive_interference_size since C++17.
Its defined as:
Minimum offset between two objects to avoid false sharing. Guaranteed to be at least alignof(std::max_align_t)
You can also try to do it programmatically by measuring some timing. Obviously, it won't always be as precise as cpuid and the likes, but it is more portable. ATLAS does it at its configuration stage, you may want to look at it: