我有以下代码,我想创建一个封装计时器的类,但我遇到的麻烦是在声明类后使用计时器。我发布了另一个代码块来显示我想如何使用计时器的示例。
double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks*1000)/CLOCKS_PER_SEC;
return diffms;
}
void some_function()
{
clock_t begin = clock();
//do something
clock_t end=clock();
cout << "Time elapsed: " << double(diffclock(end,begin)) << " ms"<< endl;
}
这是头文件
#ifndef SPECIALCLOCK_H
#define SPECIALCLOCK_H
#include <ctime>
class specialclock
{
private:
public:
specialclock(){}
~specialclock(){}
double diffclock(clock_t clock1,clock_t clock2);
};
double specialclock::diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks*1000)/CLOCKS_PER_SEC;
return diffms;
}
#endif
这是主文件
#include "specialclock.h"
int main()
{
specialclock timer;
//how would I use the timer here?
return 0;
}
答案 0 :(得分:2)
在你的specialclock类的构造函数中,将时钟的当前值存储到成员变量。
在你的specialclock类的析构函数中,再次查询时钟的当前值,从当前值中减去成员变量的值,然后打印出结果。
然后你可以在任何函数/方法的顶部声明一个特殊时钟项,它会自动打印出函数/方法运行的时间。
答案 1 :(得分:1)
#include <iostream>
#include "specialclock.h"
int main()
{
specialclock timer;
clock_t begin = clock();
//do something here
clock_t end = clock();
std::cout << "Time elapsed: " << double(timer.diffclock(end,begin)) << " ms"<< std::endl;
return 0;
}
答案 2 :(得分:1)
你设置课程的方式并没有多大意义。我有一个简单的计时器类,其工作原理如下:
Timer MyTimer;
// Do stuff...
std::cout << "Execution took " << MyTimer.Seconds() << " seconds." << std::endl;
这是你要找的吗?如果是这样,我的课程设置如下:
class Timer
{
std::clock_t ReferencePoint;
public:
Timer()
{
// Set the reference point to the current time.
}
double Seconds()
{
// Return the difference between the current time and the
// reference point.
}
};