Ali*_*gna 5 c++ linux performance cpu-cache
从这篇文章开始--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;
}
Run Code Online (Sandbox Code Playgroud)
使用步骤的各种值,我看不到运行时间的跳跃:
step, microseconds
1, 451725
2, 334981
3, 287679
4, 261813
5, 254265
6, 246077
16, 215035
32, 207410
64, 202526
128, 197089
256, 195154
Run Code Online (Sandbox Code Playgroud)
我希望看到类似的东西:
但是从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;
}
Run Code Online (Sandbox Code Playgroud)
运行工具valgrind --tool=cachegrind ./a.out $cacheline-size,您应该会看到结果。绘制此图后,您将获得准确的所需结果。快乐实验!