如何从 C++ 将某些内存范围标记为不可缓存? [英] How to mark some memory ranges as non-cacheable from C++?

查看:19
本文介绍了如何从 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++ 将某些内存范围标记为不可缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆