缓存行测试

以下截图及相关信息,均来源于马士兵公开课中

概念:

缓存行大小64子节;缓存行是CPU与内存操作的基本单元

问题:

多个CPU读取同一缓存行,分别修改缓存行中不同的数据,相互是否有影响?

实验:

多个CPU读取不同的缓存行,并对其修改的速度,对比 多个CPU 读取同一缓存行,分别修改缓存行中不同的数据。

结果:

多个CPU读取不同的缓存行,并对其修改的速度更优于多个CPU 读取同一缓存行,分别修改缓存行中不同的数据

证实:

多个CPU读取同一缓存行,分别修改缓存行中不同的数据,相互有影响

实验:

以下两个程序只有定义的 类 T 不一样;实验二多个7个long类型的值,一共64字节
实验一中:CPU读取数据修改时,修改的是同一缓存行,相互之间会影响(导致不断从内存中读取数据)
实验二中:CPU读取数据修改时,修改的是不同的缓存行,相互之间不会影响(从缓存中读取数据)
所以实验二的执行速度要优于实验一;也证实了缓存行的大小为 64 字节

实验代码一:

public class T01_CacheLinePadding {
    public static long COUNT = 10_0000_0000L;

    private static class T {
        public long x = 0L;
    }


    public static T[] arr = new T[2];

    static {
        arr[0] = new T();
        arr[1] = new T();
    }

    public static void main(String[] args) throws Exception {
        CountDownLatch latch = new CountDownLatch(2);
        Thread th1 = new Thread(() -> {
            for (long i = 0; i < COUNT; i++) {
                arr[0].x = i;
            }

            latch.countDown();
        });

        Thread th2 = new Thread(() -> {
            for (long i = 0; i < COUNT; i++) {
                arr[1].x = i;
            }
            latch.countDown();
        });

        final long start = System.nanoTime();
        th1.start();
        th2.start();
        latch.await();
        System.out.println((System.nanoTime() - start) / 10_0000);
    }
}

实验结果一:


image.png
image.png

实验代码二:

public class T02_CacheLinePadding {
    public static long COUNT = 10_0000_0000L;

    private static class T{
        public long  p1,p2,p3,p4,p5,p6,p7;
        public long x = 0L;
    }


    public static T[] arr = new T[2];

    static {
        arr[0] = new T();
        arr[1] = new T();
    }

    public static void main(String[] args) throws Exception {
        CountDownLatch latch = new CountDownLatch(2);
        Thread th1 = new Thread(()->{
            for (long i = 0;i{
            for (long i = 0;i

实验结果二:


image.png
image.png

你可能感兴趣的:(缓存行测试)