常用需求系列——C++效率计时函数

#include 
#include 
#include   
#include 
#include 

using namespace std;

timeval getTime(){
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv;
}

//计时函数,用来统计效率
string SubTimeval(timeval &end, timeval &begin)
{
    struct timeval result;
    
    if (begin.tv_sec > end.tv_sec) {
        return 0;
    }

    if ((begin.tv_sec == end.tv_sec) && (begin.tv_usec > end.tv_usec)){
        return 0;
    }

    result.tv_sec  = (end.tv_sec - begin.tv_sec);
    result.tv_usec = (end.tv_usec - begin.tv_usec);

    if (result.tv_usec < 0) {
        result.tv_sec --;
        result.tv_usec += 1000000;
    }
    
    unsigned int ret = result.tv_sec * 1000000 + result.tv_usec;
    
    string str_ret;
    if (ret >= 1000000){
        str_ret = int2str(ret/1000000) + " s " + int2str(ret/1000%1000) + " ms";
    }
    else if (ret >= 1000){
        str_ret = int2str(ret/1000) + " ms";
    } 
    else{
        str_ret = int2str(ret) + " ns";
    }
    
    return str_ret;
} 

int main()
{
    struct timeval t2 = getTime();
    func();
    struct timeval t3 = getTime();
    cout<


int2str函数请参考一条语句系列——C++ STL篇


你可能感兴趣的:(常用需求系列)