gpt4 book ai didi

C++ 函数 : Number of memory access

转载 作者:太空狗 更新时间:2023-10-29 23:04:54 36 4
gpt4 key购买 nike

我想找出由于某个函数导致的内存访问次数。为此,我正在使用 pintool。在 pintool 中,我使用了 pinatrace,但它会生成一个巨大的文件(文件大小 > 534 MB),其中包含整个程序的所有读写操作。但是我想为一个特定的功能找到它。我还没有找到任何这样做的例子。请在这方面帮助我或提供任何有用的链接。

P.S:我正在 Linux 上编译我的 c++ 程序。

最佳答案

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;
}
  1. 编译(确保使用 -g 选项)

    g++ -std=c++11 -W -Wall -g -o test test.cpp
  2. 以 cachegrind 模式运行 valgrind

    valgrind --tool=cachegrind ./test
  3. 运行 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 会生成易于阅读的输出。

关于C++ 函数 : Number of memory access,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21138258/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com