簡體   English   中英

測量緩存行大小的簡單測試

[英]Simple test to measure cache lines size

從這篇文章開始--Igor Ostrovsky 的處理器緩存效果庫 - 我想在我自己的機器上玩他的例子。 這是我的第一個示例的代碼,它查看不同緩存行如何影響運行時間:

#include <iostream>
#include <time.h>

using namespace std;

int main(int argc, char* argv[])
{
    int step = 1;

    const int length = 64 * 1024 * 1024;
    int* arr = new int[length];

    timespec t0, t1;
    clock_gettime(CLOCK_REALTIME, &t0);
    for (int i = 0; i < length; i += step) 
        arr[i] *= 3;
    clock_gettime(CLOCK_REALTIME, &t1);

    long int duration = (t1.tv_nsec - t0.tv_nsec);
    if (duration < 0)
        duration = 1000000000 + duration;

    cout<< step << ", " << duration / 1000 << endl;

    return 0;
}

使用步驟的各種值,我看不到運行時間的跳躍:

step, microseconds
1, 451725
2, 334981
3, 287679
4, 261813
5, 254265
6, 246077
16, 215035
32, 207410
64, 202526
128, 197089
256, 195154

我希望看到類似的東西:

但是從16開始,每當我們加倍步時,運行時間減半。

我在Ubuntu13,Xeon X5450上測試它並用以下代碼編譯:g ++ -O0。 我的代碼有什么問題,或者結果確實沒問題? 任何關於我缺少的東西的見解都將受到高度贊賞。

因為我看到你想觀察緩存行大小的影響,我推薦工具cachegrind,valgrind工具集的一部分。 你的方法是對的,但不接近結果。

#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;

int main(int argc, char* argv[])
{
    int step = atoi(argv[1]);

    const int length = 64 * 1024 * 1024;
    int* arr = new int[length];

    for (int i = 0; i < length; i += step) 
        arr[i] *= 3;
    return 0;
}

運行工具valgrind --tool = cachegrind ./a.out $ cacheline-size ,你應該看到結果。 繪制完成后,您將獲得准確的預期結果。 快樂實驗!!

public class CacheLine {

public static void main(String[] args) {
    CacheLine cacheLine = new CacheLine();
    cacheLine.startTesting();
}

private void startTesting() {
    byte[] array = new byte[128 * 1024];
    for (int testIndex = 0; testIndex < 10; testIndex++) {
        testMethod(array);
        System.out.println("--------- // ---------");
    }

}

private void testMethod(byte[] array) {
    for (int len = 8192; len <= array.length; len += 8192) {

        long t0 = System.nanoTime();
        for (int i = 0; i < 10000; i++) {
            for (int k = 0; k < len; k += 64) {
                array[k] = 1;
            }
        }

        long dT = System.nanoTime() - t0;
        System.out.println("len: " + len / 1024 + " dT: " + dT + " dT/stepCount: " + (dT) / len);
    }
}
}

此代碼可幫助您確定L1數據高速緩存大小。 您可以在此處詳細了解它。 https://medium.com/@behzodbekqodirov/threading-in-java-194b7db6c1de#.kzt4w8eul

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM