测量caching行大小的简单testing

从本文开始 – Igor Ostrovsky 处理器caching效果图库 – 我想在自己的机器上玩他的例子。 这是我第一个例子的代码,它看着不同的caching行是如何影响运行时间的:

#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上testing它,然后用下面的代码编译:g ++ -O0。 我的代码有什么缺陷,或者结果确实没问题? 任何有关我失踪的见解将不胜感激。

正如我看到你想要观察缓存行大小的效果,我推荐使用valgrind工具集的一部分工具cachegrind。 你的方法是正确的,但不接近结果。

 #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