C/C++工具类快速输出函数运行时间方便优化和查找问题

平常想输出一下函数的运行时间都是这么做的:

void fuction Test()
{
	clock_t start = clock();


	do somthing...


	cout << clock() - start ;
}

后来觉得这些重复的操作是在没有必要,想弄个更方便的,于是就有了下面这个类

#include <stdio.h>
#include <iostream>

#include<ctime>
using namespace std;


class CShowRunTime
{
public:
    clock_t start;
    const char* func;
    const char* t = "test char ~";
    CShowRunTime(const char* func1)
    {
        start = clock();
        cout << "[START] :" << start << endl;
        func = func1;
    }
    
    ~CShowRunTime()
    {
        cout << "[END]FuncName:" << func << " ,useTime:" << clock() << " / " <<clock() - start << endl;
    }
    
};


#define SHOW_FUNC_TIME  const char* fname = __FUNCTION__; CShowRunTime _srf(fname);

在目标函数执行完毕的这个工具类析构的时候输出结果。

一行代码就行,看看怎么用:

void Test()
{
    SHOW_FUNC_TIME //只需要这么一行定义就好了。
    cout << "runinig ..." << endl;
    
    int a = 0;
    for(int i = 0; i< 10000000 ; i++)
        a += i;
        
    cout << "end ..." << endl;
}

int main()
{
    Test();
  
  return 0;
}

输出:

[START] :3467
runinig ...
end ...
[END]FuncName:Test ,useTime:23439 / 19972

猜你喜欢

转载自blog.csdn.net/Yang9325/article/details/123923115