Make the code more readable with a decorator?

For example, I have a function like this that does some useful work (for modeling using events):

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

      

If I need performance measurements of this useful_work

, I have to do:

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

      

This approach makes the code more clunky. Is there a way patters can do these counts outside int function()

to make the code clearer?

+3


source to share


1 answer


You can create your own decorator as shown below:

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

      



Edit: I'm not sure how your functions work count_time

and count_X_metrics

, but if you need something more complex or a way to track state, you can create an object that will do the job for you. This is definitely different from what you want, but hopefully it conveys the point I'm trying to do:

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

      

+4


source







All Articles