c++ - 如何找到这个函数的执行次数?
问题描述
我想找到这个函数执行的次数。cc文件中的函数是:
CacheSetLRU::CacheSetLRU(
CacheBase::cache_t cache_type,
UInt32 associativity, UInt32 blocksize, CacheSetInfoLRU* set_info, UInt8 num_attempts)
: CacheSet(cache_type, associativity, blocksize)
, m_num_attempts(num_attempts)
, m_set_info(set_info)
{
m_lru_bits = new UInt8[m_associativity];
for (UInt32 i = 0; i < m_associativity; i++)
m_lru_bits[i] = i;
}
相关的头文件有以下几行:
class CacheSetLRU : public CacheSet
{
public:
CacheSetLRU(CacheBase::cache_t cache_type,
UInt32 associativity, UInt32 blocksize, CacheSetInfoLRU* set_info, UInt8 num_attempts);
virtual ~CacheSetLRU();
virtual UInt32 getReplacementIndex(CacheCntlr *cntlr);
void updateReplacementIndex(UInt32 accessed_index);
protected:
const UInt8 m_num_attempts;
UInt8* m_lru_bits;
CacheSetInfoLRU* m_set_info;
void moveToMRU(UInt32 accessed_index);
};
我确实声明了一个静态整数并用 cout 得到了数字,但我只想要最后一个数字,我不知道该怎么做。我已经搜索并挖掘了每个论坛,但这些方法并没有在我的代码上产生结果。此代码是开源模拟器核心代码的一部分。
任何帮助或提示将不胜感激。
解决方案
您可以自己创建一个Recorder
类型,将其作为具有静态生命周期的对象放置在函数中,并让其析构函数输出使用次数。例如:
#include <iostream>
template <typename T>
struct Recorder {
T data;
~Recorder() {
std::cout << data << "\n";
}
};
struct Foo {
void bar() const {
static Recorder<unsigned> recorder = {0};
recorder.data += 1;
(void)(1+2); // do your thing in your function ...
}
};
int main() {
Foo foo;
foo.bar();
Foo().bar();
}
运行它会产生:
$ g++ -Wall -Wextra -pedantic -std=c++17 -O3 a.cpp && ./a.out
2
请注意,您可以根据需要添加尽可能多的语法糖,也可以为尽可能多的函数实例化它。在施工期间给它某种标识符。例如:
template <typename T, typename Identifier = std::string>
struct Recorder {
T data;
Identifier identifier = Identifier();
~Recorder() {
std::cout << identifier << ": called " << data << " times\n";
}
};
推荐阅读
- python - Python for循环求和函数麻烦
- laravel - 磁盘 [google-drive] 没有配置驱动程序
- excel - 将 Apache Solr 与 Excel 中的“元数据”和 DropBox 中的文件一起使用
- javascript - 从 JSON 对象创建一个新数组
- c - 有没有办法将 ac 代码中的一组给定功能(或基本块)划分为两个处理器?
- java - 如何在 Stream.Concat 之后流式传输内容以避免中间列表
- javascript - 通过选择一个选择框中的元素,无法选择另一个选择框,即另一个选择框将处于隐藏格式
- java - 如何让 IntelliJ CE 的 Java 语法高亮更加丰富多彩?
- javascript - 如何将事件从 webview 内的网站发送到 Nativescript 应用程序?
- spring-boot - Spring Boot - 在不同端口上启动 2 个 Tomcat 服务