在 C++ 中有没有办法确定 CPU 的缓存大小?我有一个处理大量数据的算法,我想将这些数据分解成 block ,以便它们适合缓存。这可能吗? 您能否给我任何其他有关考虑缓存大小的编程提示(尤其是在多线程/多核数据处理方面)?
谢谢!
最佳答案
根据 Ulrich Drepper 的“What every programmer should know about memory”,您可以在 Linux 上执行以下操作:
Once we have a formula for the memory requirement we can compare it with the cache size. As mentioned before, the cache might be shared with multiple other cores. Currently {There definitely will sometime soon be a better way!} the only way to get correct information without hardcoding knowledge is through the /sys filesystem. In Table 5.2 we have seen the what the kernel publishes about the hardware. A program has to find the directory:
/sys/devices/system/cpu/cpu*/cache
这在 Section 6: What Programmers Can Do 中列出.
他还在图 6.5 下方描述了一个简短的测试,如果您无法从操作系统中获取 L1D 缓存大小,可以使用该测试来确定它。
我在他的论文中还遇到了一件事情:sysconf(_SC_LEVEL2_CACHE_SIZE)
是 Linux 上的一个系统调用,它应该返回 L2 缓存大小,尽管它看起来不太好记录在案。
关于C++ 缓存感知编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1922249/