【发布时间】:2017-09-19 10:25:21
【问题描述】:
据说对于普通的x86 cpu(i7 mac),cpu cacheline大小是64bytes,所以如果使用数组大小
下面是我的程序:
#include<sys/time.h>
#include<stdlib.h>
#include<stdio.h>
size_t cacheline=16;
int main(int argc,char*argv[]){
size_t loopCount=2000000000;
if(argc==2){loopCount=atol(argv[1]);}
printf("loop=%ld\n",loopCount);
int array[cacheline];
for(size_t a=0;a<cacheline;++a){
array[a]=a;
}
size_t c=0;
long sum=1;
for(size_t i=0;i<loopCount;++i){
if(c==cacheline)c=0;
sum+=array[c++];//
}
printf("sum=%ld\n",sum);
return 0;
}
clang++ test07_cacheline.cpp -O2 -o test07_cacheline && time ./test07_cacheline 2000000000
loop=2000000000
sum=63354543092609
real 0m2.810s
user 0m2.794s
sys 0m0.009s
但在我的测试程序中我发现,无论我将“数组”的大小设置为16、64、256还是65536,时间执行时间基本相同。理论或我的程序设计有什么问题?我还尝试了一些来自互联网的其他程序,结果相同,如下:
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
long timediff(clock_t t1,clock_t t2){
return (t2-t1)*1000/CLOCKS_PER_SEC;
}
int main(int argc,char*argv[]){
int array_size=65536;
if(argc>=2)array_size=atoi(argv[1]);
int repeat_times=2000000000;
long array[array_size];
for(int i=0;i<array_size;++i){
array[i]=i;
}
int j=0;
int k=0;
int c=0;
clock_t start=clock();
while(j++<repeat_times){
if(k==array_size){k=0;}
c+=array[k++];
}
clock_t end=clock();
printf("c=%d,%lu\n",c,timediff(start,end));
return 0;
}
g++ test08_cacheline.cpp -O2 -o test08_cacheline && ./test08_cacheline
c=1865233920,2800
不管array_size如何位。那么关于缓存线如何影响我的程序性能的任何解释?
【问题讨论】:
-
只是为了确保:您是否在启用优化的情况下进行编译?另外,你是如何在你的第一个程序中测量时间的?我没有看到任何计时代码,如果您将程序作为一个整体进行测量,您的结果可能会因您对
printf等的调用而被抛出。 -
您显示的代码似乎在 c 中,但您已用 c++ 标记了这个问题。请相应地编辑标签。
-
我将标签更改为 c。我用 -O2 编译,只是我的编辑。谢谢。
标签: c linux performance caching size