第1章 跟踪实例.背景

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

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值