C/C++ tools quickly output function running time to facilitate optimization and find problems

This is how you usually want to output the running time of a function:

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


	do somthing...


	cout << clock() - start ;
}

Later, I felt that these repeated operations were unnecessary, and I wanted to make something more convenient, so I created the following class

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

Output the result when the tool class is destructed after the target function is executed.

Just one line of code, let’s see how to use it:

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;
}

output:

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

Guess you like

Origin blog.csdn.net/Yang9325/article/details/123923115