How to mark some memory ranges as non-cacheable from C++?(如何从 C++ 将某些内存范围标记为不可缓存?)
问题描述
我在这里阅读了关于 CPU 缓存的维基百科:http://en.wikipedia.org/wiki/CPU_cache#更换政策
I was reading the wikipedia on the CPU cache here: http://en.wikipedia.org/wiki/CPU_cache#Replacement_Policies
将某些内存范围标记为不可缓存可以通过避免缓存很少重新访问的内存区域来提高性能.这避免了将某些内容加载到缓存中的开销,而无需任何重用.
Marking some memory ranges as non-cacheable can improve performance, by avoiding caching of memory regions that are rarely re-accessed. This avoids the overhead of loading something into the cache, without having any reuse.
现在,我一直在阅读和学习如何编写具有更好缓存性能的程序(一般考虑,通常不特定于 C++),但我不知道高级代码可以显式地与 CPU 缓存行为交互.所以我的问题是,有没有办法用 C++ 来完成我从那篇文章中引用的内容?
Now, I've been reading and learning about how to write programs with better cache performance (general considerations, usually not specific to C++), but I did not know that high-level code can interact with CPU caching behavior explicitly. So my question, is there a way to do what I quoted from that article, in C++?
此外,我很感激有关如何专门在 C++ 中提高缓存性能的资源,即使它们不使用任何直接处理 CPU 缓存的函数.例如,我想知道使用过多级别的间接性(例如,指向容器的指针的容器)是否会损害缓存性能.
Also, I would appreciate resources on how to improve cache performance specifically in C++, even if they do not use any functions that deal directly with the CPU caches. For example, I'm wondering if using excessive levels of indirection (eg., a container of pointers to containers of pointers) can damage cache performance.
推荐答案
在 Windows 上,您可以使用 VirtualProtect(ptr, length, PAGE_NOCACHE, &oldFlags)
设置内存的缓存行为以避免缓存.
On Windows, you can use VirtualProtect(ptr, length, PAGE_NOCACHE, &oldFlags)
to set the caching behavior for memory to avoid caching.
关于过多的间接访问:是的,如果您经常访问不同的内存片段(这是通常发生的情况),它们会损害缓存性能.但是,重要的是要注意,如果您始终取消引用 相同 集的 e.g.8块内存,只有第9块不同,那么一般不会有什么区别,因为8块内存会在第一次访问后缓存.
Regarding too many indirections: Yes, they can damage cache performance, if you access different pieces of memory very often (which is what happens usually). It's important to note, though, that if you consistently dereference the same set of e.g. 8 blocks of memory, and only the 9th block differs, then it generally won't make a difference, because the 8 blocks would be cached after the first access.
这篇关于如何从 C++ 将某些内存范围标记为不可缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 C++ 将某些内存范围标记为不可缓存?
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01