clflush
CPU 指令不知道你的结构体的大小;它只刷新一个缓存行,即包含指针操作数指向的字节的缓存行。(C 内在函数将其公开为const void*
,但char*
也有意义,特别是考虑到将其描述为 8 位内存操作数的asm 文档。)
您需要 4 次刷新 64 字节,或者如果您的结构不是,则可能需要 5 次alignas(64)
,因此它可以在 5 个不同的行中有部分。(您可以无条件地刷新结构的最后一个字节,而不是使用更复杂的逻辑来检查它是否在您尚未刷新的缓存行中,这取决于clflush
与更多逻辑的相对成本和可能的分支错误预测。)
您的原始循环在您的结构开始时对 4 个相邻字节进行了 4 次刷新。
使用指针增量可能是最简单的,因此转换不会与关键逻辑混淆。
// first attempt, a bit clunky:
const int LINESIZE = 64;
const char *lastbyte = (const char *)(&mystruct+1) - 1;
for (const char *p = (const char *)&mystruct; p <= lastbyte ; p+=LINESIZE) {
_mm_clflush( p );
}
// if mystruct is guaranteed aligned by 64, you're done. Otherwise not:
// check if next line to maybe flush contains the last byte of the struct; if not then it was already flushed.
if( ((uintptr_t)p ^ (uintptr_t)lastbyte) & -LINESIZE == 0 )
_mm_clflush( lastbyte );
x^y
在它们不同的位位置上为 1。 x & -LINESIZE
丢弃地址的行内偏移位,仅保留行号位。因此,我们可以仅使用 XOR 和 TEST 指令查看 2 个地址是否在同一缓存行中。(或者clang将其优化为更短的cmp
指令)。
或者将其重写为单个循环,使用该 if 逻辑作为终止条件:
我使用了 C++struct foo &var
参考,因此我可以遵循您的&var
语法,但仍然可以看到它如何为采用指针 arg 的函数进行编译。适应 C 语言很简单。
循环遍历任意大小未对齐结构的每个缓存行
/* I think this version is best:
* compact setup / small code-size
* with no extra latency for the initial pointer
* doesn't need to peel a final iteration
*/
inline
void flush_structfoo(struct foo &mystruct) {
const int LINESIZE = 64;
const char *p = (const char *)&mystruct;
uintptr_t endline = ((uintptr_t)&mystruct + sizeof(mystruct) - 1) | (LINESIZE-1);
// set the offset-within-line address bits to get the last byte
// of the cacheline containing the end of the struct.
do { // flush while p is in a cache line that contains any of the struct
_mm_clflush( p );
p += LINESIZE;
} while(p <= (const char*)endline);
}
使用 x86-64 的 GCC10.2 -O3,可以很好地编译(Godbolt)
flush_v3(foo&):
lea rax, [rdi+255]
or rax, 63
.L11:
clflush [rdi]
add rdi, 64
cmp rdi, rax
jbe .L11
ret
alignas(64) struct foo{...};
如果不幸使用,GCC 不会展开,也不会更好地优化。您可以使用if (alignof(mystruct) >= 64) { ... }
检查是否需要特殊处理以让 GCC 更好地优化,否则只需使用end = p + sizeof(mystruct);
或end = (const char*)(&mystruct+1) - 1;
类似的。
(在 C 中, # #include <stdalign.h>
define for alignas()
and alignof()
like C++,而不是 ISO C11_Alignas
和_Alignof
关键字。)
另一种选择是这样,但它更笨重并且需要更多的设置工作。
const int LINESIZE = 64;
uintptr_t line = (uintptr_t)&mystruct & -LINESIZE;
uintptr_t lastline = ((uintptr_t)&mystruct + sizeof(mystruct) - 1) & -LINESIZE;
do { // always at least one flush; works on small structs
_mm_clflush( (void*)line );
line += LINESIZE;
} while(line < lastline);
一个 257 字节的结构总是恰好接触 5 个缓存行,不需要检查。或者一个 260 字节的结构,已知它是由 4 对齐的。IDK 如果我们可以让 GCC 基于此优化检查。