以编程方式获取缓存行大小?

欢迎所有平台,请指定您的回答平台.

All platforms welcome, please specify the platform for your answer.

一个类似的问题:如何在 C++ 中以编程方式获取 CPU 缓存页面大小?

推荐答案

在 Linux(具有相当新的内核)上,您可以从/sys 中获取此信息:

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

这为您提供了有关缓存的更多信息,您可能希望知道,包括缓存行大小 (coherency_line_size) 以及哪些 CPU 共享此缓存.如果您正在使用共享数据进行多线程编程,这将非常有用(如果共享数据的线程也共享缓存,您将获得更好的结果).

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

相关文章