原文转载自:http://blog.csdn.net/ljbkiss/article/details/7378392
最开始的C接口中的是 cvGetTickCount()和 cvGetTickFrequency(),在程序段的开始和结束时两次使用cvGetTickCount(),然后将两次的差除以cvGetTickFrequency()后就可以获得程序段的以微秒us为单位的运行时间,不是很精确但是一般足够了。
C++接口中还将上面的函数封装为了一个类TickMeter,方便使用,下面是关于TickMeter的声明和实现的源码:
//#include<contrib/contrib.hpp>
class CV_EXPORTS TickMeter
{
public:
TickMeter();
void start();
void stop();
int64 getTimeTicks() const;
double getTimeMicro() const;
double getTimeMilli() const;
double getTimeSec() const;
int64 getCounter() const;
void reset();
private:
int64 counter;
int64 sumTime;
int64 startTime;
};
CV_EXPORTS std::ostream& operator<<(std::ostream& out, const TickMeter& tm);
//Spinimages.cpp
cv::TickMeter::TickMeter() { reset(); }
int64 cv::TickMeter::getTimeTicks() const { return sumTime; }
double cv::TickMeter::getTimeMicro() const { return (double)getTimeTicks()/cvGetTickFrequency(); }
double cv::TickMeter::getTimeMilli() const { return getTimeMicro()*1e-3; }
double cv::TickMeter::getTimeSec() const { return getTimeMilli()*1e-3; }
int64 cv::TickMeter::getCounter() const { return counter; }
void cv::TickMeter::reset() {startTime = 0; sumTime = 0; counter = 0; }
void cv::TickMeter::start(){ startTime = cvGetTickCount(); }
void cv::TickMeter::stop()
{
int64 time = cvGetTickCount();
if ( startTime == 0 )
return;
++counter;
sumTime += ( time - startTime );
startTime = 0;
}
std::ostream& cv::operator<<(std::ostream& out, const TickMeter& tm){ return out << tm.getTimeSec() << "sec"; }
测试实例:
#include<iostream>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<contrib/contrib.hpp>
using namespace cv;
using namespace std;
int main()
{
TickMeter tm;
tm.start();
Mat img1 = imread("1.jpg");
namedWindow("img1", CV_WINDOW_NORMAL);
setWindowProperty("img1", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
imshow("img1", img1);
//waitKey(3000);
tm.stop();
cout << "count=" << tm.getCounter() << " ,process time=" << tm.getTimeMilli() << endl;
return 0;
}
可以看出TickMeter仅仅是将C接口的函数进行了一下封装,不过使用时就方便多了,不用去反复gettickcount然后除以frequency了,只需要在开始时调用start();结束时调用stop(),然后如果需要以us为单位的运行时间就调用getTimeMicro(),以ms为单位的就调用getTimeMilli(),以s为单位的是getTimeSec(),而getTimeTicks()返回运行时间的tickcount,getTimeTicks()返回的是调用stop的次数,同时该类还重载了ostream,可以方便的以s为单位直接输出。
【NOTE!TickMeter对象的计时是累积的,如果要分段计时的话,获取运行时间之后,下一次调用start()之前需要调用reset()将计时归零,否则获得的时间是累积运行时间】