繁体   English   中英

如何演示缓存未命中?

[英]How can I demonstrate cache misses?

迈耶斯的启发我正在阅读计算机缓存并希望进行实验,这表明了所提到的事情。 这是我尝试过的:

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

int main(void)
{
    typedef uint8_t data_t;

    const uint64_t max = (uint64_t)1<<30;
    const unsigned cycles = 1000;
    const uint64_t step = 63;  // tried also for 64

    volatile data_t acu = 0;
    volatile data_t *arr = malloc(sizeof(data_t) * max);
    for (uint64_t i = 0; i < max; ++i)
        arr[i] = ~i;

    for(unsigned c = 0; c < cycles; ++c)
        for (uint64_t i = 0; i < max; i += step)
            acu += arr[i];

    printf("%lu\n", max);

    return 0;
}

Anbd然后只是gcc --std=c99 -O0 test.c && time ./a.out 我检查过,我的CPU缓存行长64个字节。 通过分配step = 64我试图比step=63更频繁地生成缓存未命中。

但是, step=63实际上运行速度稍快。 我怀疑我是预取的“受害者”,因为我的RAM读取是顺序的。

如何改进我走数组的例子,以证明缓存未命中的成本?

使用step = 63时,仍会遇到大量缓存未命中。 前两次访问将在同一个缓存行上,但接下来的63次访问将导致缓存未命中,访问该行的第63,6,61 ......字节。 测量它的更好方法是显示step = 1 (几乎没有缓存未命中)和step = 64 (总是缓存未命中)之间的差异,并调整max以获得总访问次数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM