C++ 如何找到该函数的执行次数?

C++ 如何找到该函数的执行次数?,c++,c++11,C++,C++11,我想找出这个函数执行的次数。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_attem

我想找出这个函数执行的次数。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;

}
我确实声明了一个静态整数,用cout得到了数字,但我只想要最后一个数字,我不知道怎么做。我已经搜索和挖掘了每个论坛,但是这些方法并没有在我的代码中产生结果。此代码是开源模拟器核心代码的一部分。

如有任何帮助或提示,将不胜感激

您可以自己创建一个
记录器
类型,将其作为具有静态生存期的对象放置在函数中,并让其析构函数输出使用次数。例如:

#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();
}

请注意,您可以根据自己的喜好为其添加任意多的语法糖,也可以根据自己的喜好为其实例化任意多的函数。在构建过程中为其提供某种标识符。例如:

template <typename T, typename Identifier = std::string>
struct Recorder {
  T data;
  Identifier identifier = Identifier();
  ~Recorder() {
    std::cout << identifier << ": called " << data << " times\n";
  }
};
模板
结构记录器{
T数据;
标识符=标识符();
~Recorder(){

std::您是否尝试将静态变量打印为
main
中发生的最后一件事?这可能会得到最后一个数字。有什么特别阻止您声明计数器、在此函数中递增计数器,然后在
main()之前打印此计数器的值
终止?您所说的“我只想要最后一个号码”到底是什么意思?这里只有一个数字,这个函数被调用的次数。你的问题不清楚。全局
int counter=0;
在关注点
++counter;
。就在main完成之前,
std::cout@john I无法声明新的主函数,因为主函数是在模拟器的另一个代码中声明的因此,由于模拟器的限制,使模拟器得到重复的声明错误。谢谢您的评论。@SamVarshavchik,正如我提到的这段代码,是模拟器数千个代码文件代码的一部分,我不能声明新的
main()
函数,因为另一个代码文件中有一个。我可以在此函数中使用此代码:
static int I;
std::cout
$ 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";
  }
};