给出三种比较精确的计时方式,使用纯C语言,使用Boost和OpenCV的库函数。
// pure c
#if defined(_WIN32) && defined(_MSC_VER)
#include <windows.h>
double abtic() {
__int64 freq;
__int64 clock;
QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
QueryPerformanceCounter((LARGE_INTEGER *)&clock);
return ((double)clock / double(freq)) * 1.E6;
}
#else
#include <time.h>
#include <sys/time.h>
double abtic() {
double result = 0.0;
struct timeval tv;
gettimeofday(&tv, NULL);
result = tv.tv_sec * 1000 * 1000 + tv.tv_usec;
return result;
}
#endif /* _WIN32 */
#define __PUREC_TB(A) double A = abtic()
#define __PUREC_TE(A) cout << #A << " : elapsed = " << (abtic()-A)*1.E-3 << "ms" << endl
// with Boost
#include <boost/timer/timer.hpp>
#define __BOOST_TB(A) boost::timer::cpu_timer (A); (A).start()
#define __BOOST_TE(A) A.stop(); cout << #A << " : Wall = " << ((A).elapsed().wall)*1.E-6 << "ms, User = " << ((A).elapsed().user)*1.E-6 << "ms, System = " << ((A).elapsed().system)*1.E-6 << "ms" << endl
// with OpenCV
#include <opencv2/opencv.hpp>
#define __CV_TB(A) int64 A = cv::getTickCount();
#define __CV_TE(A) cout << #A << " : elapsed = " << (double)(cv::getTickCount()-A)/(cv::getTickFrequency())*1.E3 << "ms" << endl
__PUREC_TB(purec);
... // some code
__PUREC_TE(purec);
__BOOST_TB(with_boost);
... // some code
__BOOST_TE(with_boost);
__CV_TB(with_OpenCV);
... // some code
__CV_TE(with_OpenCV);