首页 > 解决方案 > 如何找到这个函数的执行次数?

问题描述

我想找到这个函数执行的次数。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 得到了数字,但我只想要最后一个数字,我不知道该怎么做。我已经搜索并挖掘了每个论坛,但这些方法并没有在我的代码上产生结果。此代码是开源模拟器核心代码的一部分。
任何帮助或提示将不胜感激。

标签: c++c++11

解决方案


您可以自己创建一个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";
  }
};

推荐阅读