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).