gpt4 book ai didi

c++ - 用装饰器让代码更清晰?

转载 作者:太空狗 更新时间:2023-10-29 20:53:13 26 4
gpt4 key购买 nike

例如,我有这样的函数可以执行一些有用的工作(对于事件驱动模拟):

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

关于c++ - 用装饰器让代码更清晰?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43458024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com