到了2.x之后在命名空间cv中又多了几个函数,getTickCount(),getTickFrequency(),getCPUTickCount(),此时仍然可以使用上面的C接口的函数,也可以使用这几个namespace cv中的函数,两次使用getTickCount(),然后再除以getTickFrequency(),不过需要注意的是这时计算出来的是以秒s为单位的时间,这个是与上面的带cv前缀的函数的不同,而要使用更精确的计时,就需要使用getCPUTickCount(),不过现代计算机CPU的频率会随着负载而变化所以没大有必要使用该函数,可以参看函数的介绍【Also, since a modern CPU varies the CPU frequency depending on the load, the number of CPU clocks spent in some code cannot be directly converted to time units. Therefore,getTickCount is generally a preferable solution for measuring execution time.】也就是使用getTickCount就足够了。
同时C++接口中还将上面的函数封装为了一个类TickMeter,方便使用,下面是关于TickMeter的声明和实现的源码:
//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"; }
可以看出TickMeter仅仅是将C接口的函数进行了一下封装,不过使用时就方便多了,不用去反复gettickcount然后除以frequency了,只需要在开始时调用start();结束时调用stop(),然后如果需要以us为单位的运行时间就调用getTimeMicro(),以ms为单位的就调用getTimeMilli(),以s为单位的是getTimeSec(),而getTimeTicks()返回运行时间的tickcount,getTimeTicks()返回的是调用stop的次数,同时该类还重载了ostream,可以方便的以s为单位直接输出。
一个小例子:
TickMeter tm; tm.start(); int col=temp.cols, row = temp.rows; if (temp.isContinuous()) { col*=row; row =1; } for (i=0; i<row; ++i) { const float *pt = temp.ptr<float>(i); for (j=0; j<col;++j) { float mm=pt[3*j]; mm = mm/(float)20.6; } } tm.stop(); cout<<"count="<<tm.getCounter()<<",process time="<<tm.getTimeMilli()<<endl;