C++一些跟踪调试代码会导致性能下滑,常见会如下方式来定位, 不过这有一个问题就是你必须把源码给他们,让他们自己去编译,否则这种宏定义的方式就无法在实际工程中使用。
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstddef>
#include <string>
#include <chrono>
#include <memory>
using namespace std;
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;
class Trace
{
public:
Trace(const char* name);
~Trace();
void debug(const char* meg);
static bool traceActive;
private:
//unique_ptr<string> theFunctionName;
string* theFunctionName;
};
bool Trace::traceActive = false;
inline
Trace::Trace(const char* name)
{
if (traceActive)
{
std::cout << "Enter Function: " << theFunctionName << std::endl;
//theFunctionName=make_unique<string>(name);
theFunctionName = new string(name);
}
}
inline
void Trace::debug(const char* meg)
{
if (traceActive)
{
std::cout << "Error: " << meg << std::endl;
}
}
inline
Trace::~Trace()
{
if (traceActive)
{
std::cout << "Exit Function: " << theFunctionName << std::endl;
delete theFunctionName;
}
}
int addOne(int x)
{
const char* name = "addOne";
Trace t(name);
return x + 1;
}
// Driver Method
int main()
{
high_resolution_clock::time_point start_time = high_resolution_clock::now();
int j = 10000000;
int y = 0;
for (int i = 0; i < j; i++)
{
y = addOne(i);
}
high_resolution_clock::time_point end_time = high_resolution_clock::now();
milliseconds time_interval = std::chrono::duration_cast<milliseconds>(end_time - start_time);
cout << "run func cost " << time_interval.count() << " ms" << endl;
return 0;
}
}