您的位置:首页 > 编程语言 > C语言/C++

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

2016-09-13 15:09 351 查看
#include <map>
#include <string>
#include <vector>
#include <iostream>
#include <sys/time.h>

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<<SubTimeval(t3, t2)<<endl;
}


int2str函数请参考一条语句系列——C++ STL篇
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: