常用代码段

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bendanban/article/details/51285649

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)) * 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

// 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


// 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);

2. max_singed<>()

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

3. 待续……

猜你喜欢

转载自blog.csdn.net/bendanban/article/details/51285649