C++性能优化 —— __builtin_prefetch()数据预读
C++性能优化 —— __builtin_prefetch()数据预读
References
- __builtin_prefetch()
- [Prefetching with __builtin_prefetch]( https://developer.arm.com/documentation/101458/2010/Coding-best-practice/Prefetching-with---builtin-prefetch#:~:text=__builtin_prefetch syntax In Arm Compiler for Linux the ,syntax%3A%20__builtin_prefetch%20%28const%20void%20%2Aaddr%20%20rw%5B%2C%20locality%5D%5D%29%26%5D)
- Data Prefetch 数据预取
- 数据预读对二分查找的优化
- 你见过哪些令你瞠目结舌的C/C++代码技巧?
一、什么是 __builtin_prefetch()?
为了降低内存读取的cache-miss延迟,可以通过gcc提供的这个内置函数来预读数据。当知道数据的内存地址即将要被读取(在下一个load & store指令到来之前),在数据被处理之前,就可以在代码中通过指令通知目标,去读取数据并放到缓存中。
Note that the prefetching instruction is a hint, which means that your target processor might, or might not, actually prefetch the data.
二、用法
__builtin_prefetch (const void *addr[, rw[, locality]])
1. addr (required): 代表内存地址
-
0(default): prepare the prefetch for a read -
1: prepare the prefetch for a write to the memory
2. rw (optional) : 编译时的常量
-
0: None, the data can be removed from the cache after the access. -
1: Low, L3 cache, leave the data in the L3 cache level after the access. -
2: Moderate, L2 cache, leave the data in L2 and L3 cache levels after the access. -
3(default): High, L1 cache, leave the data in the L1, L2, and L3 cache levels after the access.
三、适用场景
适用于数据访问有较大随机性的场景。
- 数组的二分查找,此时,数组访问具有较大的随机性。
- 用来加快各种结构的迭代速度:链表、树、堆、哈希等。
- Vpp bihash预读bucket和data。
四、缺点
需要注意,软件预取是有代价的:我们的系统执行了更多的指令,并将更多的数据加载到缓存中,这在某些情况下可能会导致其他方面的性能下降。
浙公网安备 33010602011771号