gpt4 book ai didi

linux - 有没有办法检查最近是否刷新了处理器缓存?

转载 作者:IT王子 更新时间:2023-10-29 00:05:22 27 4
gpt4 key购买 nike

在 i386 Linux 上。如果可能,最好在 c/(c/posix std libs)/proc 中。如果没有,是否有任何程序集或第三方库可以做到这一点?

编辑:我正在尝试开发测试内核模块是否清除缓存行或整个处理器(使用 wbinvd())。程序以 root 身份运行,但如果可能,我更愿意留在用户空间。

最佳答案

缓存一致性系统尽最大努力向您隐藏此类内容。我认为您必须间接观察它,方法是使用性能计数寄存器来检测高速缓存未命中或使用高分辨率计时器仔细测量读取内存位置的时间。

此程序在我的 x86_64 机器上运行,以演示 clflush 的效果。它计算使用 rdtsc 读取全局变量所花费的时间。作为直接绑定(bind)到 CPU 时钟的单个指令,直接使用 rdtsc 非常适合此目的。

这是输出:

took 81 tickstook 81 ticksflush: took 387 tickstook 72 ticks

You see 3 trials: The first ensures i is in the cache (which it is, because it was just zeroed as part of BSS), the second is a read of i that should be in the cache. Then clflush kicks i out of the cache (along with its neighbors) and shows that re-reading it takes significantly longer. A final read verifies it is back in the cache. The results are very reproducible and the difference is substantial enough to easily see the cache misses. If you cared to calibrate the overhead of rdtsc() you could make the difference even more pronounced.

If you can't read the memory address you want to test (although even mmap of /dev/mem should work for these purposes) you may be able to infer what you want if you know the cacheline size and associativity of the cache. Then you can use accessible memory locations to probe the activity in the set you're interested in.

Source code:

#include <stdio.h>
#include <stdint.h>

inline void
clflush(volatile void *p)
{
asm volatile ("clflush (%0)" :: "r"(p));
}

inline uint64_t
rdtsc()
{
unsigned long a, d;
asm volatile ("rdtsc" : "=a" (a), "=d" (d));
return a | ((uint64_t)d << 32);
}

volatile int i;

inline void
test()
{
uint64_t start, end;
volatile int j;

start = rdtsc();
j = i;
end = rdtsc();
printf("took %lu ticks\n", end - start);
}

int
main(int ac, char **av)
{
test();
test();
printf("flush: ");
clflush(&i);
test();
test();
return 0;
}

关于linux - 有没有办法检查最近是否刷新了处理器缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6041271/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com