天天看點

常用代碼段

1. 計時

給出三種比較精确的計時方式,使用純C語言,使用Boost和OpenCV的庫函數。

純C

// 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)) * ;
}
#else  
#include <time.h>  
#include <sys/time.h>  
double abtic() {
    double result = ;
    struct timeval tv;
    gettimeofday(&tv, NULL);
    result = tv.tv_sec *  *  + 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

// 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)* << "ms, User = " << ((A).elapsed().user)* << "ms, System = " << ((A).elapsed().system)* << "ms" << endl
           

With OpenCV

// 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())* << "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);
           

2. max_singed<>()

#include <inttypes.h>
template <class T>
int64_t max_signed(){
    uint8_t l = sizeof(T)*-;
    int64_t r = ;
    for (uint8_t i = ; i < l; i++){
        r = (r << ) + ;
    }
    return r;
}
           
cout << "max = " <<  max_signed<int8_t>()   << endl;
cout << "min = " << -max_signed<int8_t>()- << endl;
           
max = 
min = -
           

3. 待續……