哈喽,大家好,我是呼噜噜,之前的系列文章我们分别介绍了 CPU Cache 的基本概念、组织架构以及缓存一致性协议
知其然还要知其所以然,但对开发者来说,最关键的还是如何把这些底层原理变成写出高性能代码的
今天我们就从几个实打实的经典代码案例切入,聊聊怎么在日常写代码时把CPU Cache的性能榨干。
数组遍历方式
我们先来看一个很经典的例子(例子是C语言写的,其他语言实现也都是差不多的):
#include stdio.h
#include stdlib.h
#include time.h
int main()
{
clock_t begin, end;
double cost;
begin = clock();
int count = 10000;
int* array = (int*)malloc(sizeof(int) * count * count);//2维数组
//代码1 按行遍历
//for (int i = 0;i count;i++) {
// for (int j = 0; j count; j++) {
// array[i * count + j] = 0;
// }
//}
//代码2 按列遍历
for (int i = 0;i count;i++) {
for (int j = 0; j count; j++) {
array[j * count + i] = 0;
}
}
end = clock();
cost = (double)(end - begin) / CLOCKS_PER_SEC;
printf("constant CLOCKS_PER_SEC is: %ld, time cost is: %lf", CLOCKS_PER_SEC, cost);
return 0;
}
运行结果:
#代码1
constant CLOCKS_PER_SEC is: 1000, time cost is: 0.126000
#代码2
constant CLOCKS_PER_SEC is: 1000, time cost is: 0.301000
CLOCKS_PER_SEC=1000,表示当前电脑1秒是被分成了1000个时间片,也就是说时间测量最小单位为1ms
所以上述代码1,在笔者的电脑运行耗时大约0.126ms;而代码2,运行耗时却高达0.301ms
两段代码的运算逻辑与总赋值次数完全相同,为什么按列遍历慢了一倍以上?
这2段代码块基本一致,唯独遍历方式不同,代码1是按行遍历,而代码2是按列遍历。


闽公网安备 35020602001684号