测量其他类中函数的时间
Measure time of functions in other Class
我已经阅读了如何在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);
}
};
感谢您的快速帮助!
相关文章:
- rcpp函数中的清理时间很长
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 函数的时间复杂度是多少?
- 在多个时间戳处执行函数
- 如何计算此排序函数的时间复杂度?
- C++不重载时间函数,所以我们不需要写 NULL 有什么原因吗?
- C 时间函数问题
- C 时间函数在不同的呼叫下返回相同的值
- 线程:如何在C或C++中精确计算算法的执行时间(函数的持续时间)
- 使用时间函数后,字符串已损坏
- 为srand()提供Windows的时间函数
- 快速时间函数C/C++
- 什么可能导致时间函数和 DLL 加载之间死锁
- 时间函数有时有效有时不起作用
- 任何时间函数保证为调用返回不同的值
- srand函数如何与时间函数相互作用
- 计算时间增量最快的linux C时间函数是什么?看到clock_gettime和gettimeofday表现不佳
- C++,时间函数(Linux)-纳秒分辨率
- 如何挂钩时间函数
- 使用srand和时间函数的差异