通过装饰器使代码更清晰

  • 本文关键字:代码 清晰 c++ decorator
  • 更新时间 :
  • 英文 :


int function()
{
    do_useful_work();
    return 0;
}

如果我需要对此useful_work的性能进行测量,我应该做:

int function()
{
    count_time(time_before);
    count_X_metrics(X_before);
    do_useful_work();
    count_time(time_after);
    count_X_metrics(X_after);
    return 0;
}

这种方法使代码更加笨拙。有没有办法,在int function()之外进行这些计数以使代码更清晰?

您可以按以下方式创建自己的装饰器:

#include<functional>
#include <iostream>
void count_time() {};
void count_X_metrics() {};
void decorator(std::function<void()> work)
{
    count_time();
    count_X_metrics();
    work();
    count_time();
    count_X_metrics();
}

void do_work_1() {
    std::cout << "Hello, World 1!" << std::endl;
}
void do_work_2() {
    std::cout << "Hello, World 2!" << std::endl;
}
int main() {
    decorator(do_work_1);
    decorator(do_work_2);
}

编辑:我不确定您的count_timecount_X_metrics的功能如何,但是如果您需要更复杂的东西或一种跟踪状态的方法,则可以创建一个对您有效的对象。这肯定与您需要的不同,但希望它传达了我要提出的观点:

#include<functional>
#include <iostream>
int current_time() { return 0; }
int x_metric() { return 0; }
class Timer {
    public:
    void time(std::function<void()> work) {
        // Capture state before
        int starttime = current_time();
        int startmetric = x_metric();
        work();
        // Capture state after
        int endtime = current_time();
        int endmetric = x_metric();
        // Update results
        ellapsed = endtime - starttime;
        metric = endmetric - startmetric;
        // Possibly do something with the metrics here.
        // ...
    }
    int get_ellapsed() { return ellapsed; }
    int get_metric() { return metric; }
    private:
    int ellapsed;
    int metric;
};
void do_work_1() {
    std::cout << "Hello, World 1!" << std::endl;
}
void do_work_2() {
    std::cout << "Hello, World 2!" << std::endl;
}
int main() {
    Timer t;
    t.time(do_work_1);
    // Possibly do something with the metrics here.
    // cout << t.get_ellapsed();
    t.time(do_work_2);
}

最新更新