测量其他类中函数的时间

Measure time of functions in other Class

本文关键字:时间 函数 其他 测量      更新时间:2023-10-16

我已经阅读了如何在stackflow中测量函数时间的不同方法。我希望能够为程序的所有函数调用时间测量函数,并编写了一个小的辅助类:

// helper.h
class Helper
{
public:
   Helper();
   ~Helper();
   template<class F, typename...Args>
   double funcTime(F func, Args&&... args);
};
// helper.cpp:
#include "Helper.h"
#include <chrono>
#include <utility>
typedef std::chrono::high_resolution_clock::time_point TimeVar;
#define duration(a) std::chrono::duration_cast<std::chrono::milliseconds>(a).count()
#define timeNow() std::chrono::high_resolution_clock::now()
template<typename F, typename... Args>
double Helper::funcTime(F func, Args&&... args)
{
 TimeVar t1 = timeNow();
 func(std::forward<Args>(args)...);
 return duration(timeNow() - t1);
}

如果您在同一类中调用它,则相同的代码工作得很好,但是如果我使用 main.cpp 调用它,则会生成LNK2019错误。目标是包装这个函数,以便我可以用我的任何函数调用它。我在这里做错了什么?

// main.cpp
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include "Helper.h"
using namespace std;
int countWithAlgorithm(string s, char delim) {
   return count(s.begin(), s.end(), delim);
}
int main(int argc, const char * argv[]) 
{ 
 Helper h;
 cout << "algo: " << h.funcTime(countWithAlgorithm, "precision=10", '=') << endl;
 system("pause");
 return 0;
}

谢谢你们为我指出正确的方向。我知道大多数编译器无法实例化模板函数,但不确定如何避免这种情况。tntxtnt评论帮助我在合并的助手中找到解决方案.h:

//helper.h
//
#pragma once
#include <chrono>
typedef std::chrono::high_resolution_clock::time_point TimeVar;
#define duration(a) std::chrono::duration_cast<std::chrono::nanoseconds>(a).count()
#define timeNow() std::chrono::high_resolution_clock::now()
 class Helper
 {
 public:
   Helper();
   ~Helper();
 template<class F, typename...Args>
 double funcTime(F func, Args&&... args)
 {
    TimeVar t1 = timeNow();
    func(std::forward<Args>(args)...);
    return duration(timeNow() - t1);
 }
};

感谢您的快速帮助!