C++应用系列:利用装饰器模式进行运行时间测试

4 篇文章 0 订阅

在平常做实验时,经常会遇到需要测试某个函数或个模块的运行时长,基本上每次都是在模块前后添加测时间的函数,然后输出查看,这样的工作相当繁琐,然而每次测试还是这样做的。

今天上网看到AOP相关,发现可以用AOP添加测时间功能。
又看到了代理模式和装饰器模式,发现应用装饰器模式似乎可以简单实现。

class VBase
{
public:
    virtual ~VBase(){}
    virtual void do_test() = 0;
};

class TimeTest:public VBase
{
public:
    TimeTest(VBase *p):m_ptr(p){}
    ~TimeTest()
    {
        delete m_ptr;
        m_ptr = nullptr;
    }
    virtual void do_test() override
    {
        cout << "begin the function..." << endl;
        auto time_begin = chrono::steady_clock::now();
        m_ptr->do_test();
        auto time_end = chrono::steady_clock::now();
        cout << "end the function..." << endl;
        auto duration = chrono::duration_cast<chrono::milliseconds>(time_end - time_begin);
        cout << "Cost Time(ms):  " << duration.count() << std::endl;
    }
private:
    VBase *m_ptr;
};

class class_to_test:public VBase
{
public:
    void do_test()
    {
        Sleep(1000);//放入需要测试时间的函数
    }
};



int main()
{
    //test2();

    shared_ptr<VBase> test = make_shared<TimeTest>(new class_to_test());
    test->do_test();
    return 0;
}

测试时间则使用TimeTest类,如果需要其他功能则可以另外创建类,继承于VBase,同时智能指针参数为该类。
输出:
begin the function…
end the function…
Cost Time(ms): 1000

略微有点搞不清装饰器模式、代理模式、AOP之间的差别。
个人理解是:
装饰器模式:给某一个类增加功能,不改变原有类,需要新功能了才利用装饰类去装饰,重点在于能够不改变原类功能而获得新功能。使用时用户将被装饰类作为参数传入给装饰器。
代理模式:访问类时增加控制权限,为原类服务的,重点在于原类。使用时,将用户与原类隔离,用户直接访问代理类,并不知道原类的细节。
AOP:面向切面编程,是否可以理解为,代理模式是AOP的一种简单实现?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值