用linux perf命令来分析程序的cpu cache miss现象

本文通过两个小程序对比,分析了在C/C++中按行访问数组与按列访问数组的效率差异,并通过time命令与perf工具展示了不同访问方式对程序运行时间和缓存缺失的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     先来看一段简单的程序:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv)
{
	int a[1000][1000];
	if(1 == argc)
	{
		for(int i = 0; i < 1000; ++i)
		{
				for(int j = 0; j < 1000; ++j)
				{
						a[i][j] = 0;
				}
		}
	}
	else
	{
		for(int i = 0; i < 1000; ++i)
		{
				for(int j = 0; j < 1000; ++j)
				{
						a[j][i] = 0;
				}
		}
	}

	return 0;
}

       上面有两个小程序片段, 哪段效率高? 显然, 第一段效率高, 为什么呢? 因为在C/C++中,数组是按行存储的,程序的按行访问可以充分利用程序的局部性原理(空间局部性), 用time命令来看看结果:

taoge$ time ./a.out 

real    0m0.006s
user    0m0.004s
sys     0m0.000s
taoge$ time ./a.out 

real    0m0.006s
user    0m0.004s
sys     0m0.000s
taoge$ time ./a.out 

real    0m0.006s
user    0m0.004s
sys     0m0.000s
taoge$ time ./a.out 1

real    0m0.009s
user    0m0.004s
sys     0m0.008s
taoge$ time ./a.out 1

real    0m0.010s
user    0m0.004s
sys     0m0.004s
taoge$ time ./a.out 1

real    0m0.010s
user    0m0.004s
sys     0m0.004s

        显然, 第二段程序的real time要大, 用perf分析下原因:

taoge$ perf stat -e L1-dcache-load-misses ./a.out

 Performance counter stats for './a.out':

           101,870 L1-dcache-load-misses                                       

       0.005415735 seconds time elapsed

taoge$ 
taoge$ 
taoge$ perf stat -e L1-dcache-load-misses ./a.out

 Performance counter stats for './a.out':

           100,231 L1-dcache-load-misses                                       

       0.005486385 seconds time elapsed

taoge$ 
taoge$ 
taoge$ perf stat -e L1-dcache-load-misses ./a.out

 Performance counter stats for './a.out':

           103,496 L1-dcache-load-misses                                       

       0.005329914 seconds time elapsed

taoge$ 
taoge$ 
taoge$ perf stat -e L1-dcache-load-misses ./a.out 1

 Performance counter stats for './a.out 1':

         1,122,333 L1-dcache-load-misses                                       

       0.012910445 seconds time elapsed

taoge$ 
taoge$ 
taoge$ perf stat -e L1-dcache-load-misses ./a.out 1

 Performance counter stats for './a.out 1':

         1,093,971 L1-dcache-load-misses                                       

       0.009197791 seconds time elapsed

taoge$ 
taoge$ 
taoge$ perf stat -e L1-dcache-load-misses ./a.out 1

 Performance counter stats for './a.out 1':

         1,099,561 L1-dcache-load-misses                                       

       0.009234823 seconds time elapsed

taoge$ 

       显而易见了,  cache miss太多了。

       理论联系实际地理解一下, 有好处。

 

 

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值