Cachegrind,它是 Valgrind 的一部分,测量(或者更确切地说,模拟)缓存访问次数以及缓存未命中(即访问实际 RAM)。查找概览here。
它可以在this format 中逐行输出您的代码的注释版本,以及缓存访问次数和缓存未命中次数。
Valgrind 包含在流行操作系统的包管理器中,并且易于安装。
这是一个例子:
#include <random>
#include <vector>
int main()
{
std::vector<int> vec;
// Seed with a real random value, if available
std::random_device rd;
std::default_random_engine eng(rd());
std::uniform_int_distribution<int> dist(1,10000);
for (std::size_t i = 0 ; i < 1000 ; ++i)
vec.push_back(dist(eng));
for (auto &num : vec)
num *= 3;
return 0;
}
-
编译(确保使用 -g 选项)
g++ -std=c++11 -W -Wall -g -o test test.cpp
-
在 cachegrind 模式下运行 valgrind
valgrind --tool=cachegrind ./test
-
运行 cg_annotate 工具:
cg_annotate ./cachegrind.out.2543 /absolute/path/test.cpp
这会产生:
==2438== Cachegrind, a cache and branch-prediction profiler
==2438== Copyright (C) 2002-2012, and GNU GPL'd, by Nicholas Nethercote et al.
==2438== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==2438== Command: ./test
==2438==
--2438-- warning: L3 cache found, using its data for the L2 simulation.
==2438==
==2438== I refs: 1,686,675
==2438== I1 misses: 1,160
==2438== LLi misses: 1,095
==2438== I1 miss rate: 0.06%
==2438== LLi miss rate: 0.06%
==2438==
==2438== D refs: 676,987 (458,995 rd + 217,992 wr)
==2438== D1 misses: 12,616 ( 11,023 rd + 1,593 wr)
==2438== LLd misses: 6,338 ( 5,272 rd + 1,066 wr)
==2438== D1 miss rate: 1.8% ( 2.4% + 0.7% )
==2438== LLd miss rate: 0.9% ( 1.1% + 0.4% )
==2438==
==2438== LL refs: 13,776 ( 12,183 rd + 1,593 wr)
==2438== LL misses: 7,433 ( 6,367 rd + 1,066 wr)
==2438== LL miss rate: 0.3% ( 0.2% + 0.4% )
注意 1:Cachegrind 模拟缓存行为,因此其输出可能并不完全准确。特别是,模拟仅考虑您正在分析的过程;它忽略操作系统/内核活动和其他进程。
注意 2:Cachegrind 也可能会生成一个大的中间文件。因此,如果您的问题是空间要求,Cachegrind 可能不是一个好的解决方案。但是,如果您的问题仅仅是输出的格式和可读性,它会有所帮助,因为 cg_annotate 会生成易于阅读的输出。