【发布时间】:2019-09-13 11:33:32
【问题描述】:
我试图减少我的 C 程序中的代码重复,其中 if/else 块的每个分支中的所有语句都是相同的,除了函数名及其参数。这个想法是用户指定x、y 或z,程序测量运行func_x、func_y 或func_z 1000 次所需的时间。
更具体地说,这里是 C 代码的高级设计:
// struct definitions
struct dat_x {...};
struct dat_y {...};
struct dat_z {...};
// reading structs from a text file
struct dat_x read_dat_x_from_file(char *path);
struct dat_y read_dat_y_from_file(char *path);
struct dat_z read_dat_z_from_file(char *path);
// functions
int func_x(struct dat_x);
int func_y(struct dat_y);
int func_z(struct dat_z);
// runner computing runtime of func_x, func_y, or func_z
int main(int argc, char** argv) {
char *func_name = argv[1];
char *path = argv[2];
int a;
clock_t t;
if (strcmp(func_name, "x") == 0) {
struct dat_x args = read_dat_x_from_file(path);
t = clock();
for (int i = 0; i < 1000; i++) {
a += func_x(args);
}
t = clock() - t;
} else if (strcmp(func_name, "y") == 0) {
struct dat_y args = read_dat_y_from_file(path);
t = clock();
for (int i = 0; i < 1000; i++) {
a += func_y(args);
}
t = clock() - t;
} else if (strcmp(func_name, "z") == 0) {
struct dat_z args = read_dat_z_from_file(path);
t = clock();
for (int i = 0; i < 1000; i++) {
a += func_z(args);
}
t = clock() - t;
}
// report runtime
double e = ((double)t) / CLOCKS_PER_SEC;
printf("%s: %f %d\n", func_name, e, a);
}
如您所见,在main 函数中,if-else 块的每个分支中的所有语句都是相同的;唯一的区别是func_x、func_y 或func_z。
在函数式语言中,这个模式可以通过一个函数run_timing_benchmark 来抽象化,它接受func_* 和dat_* 参数并且hten 运行循环(可能使用多态性来定义g 的签名)。虽然我可以在 C 中使用函数指针,但我不能编写多态类型签名。
关于如何减少此程序中的重复以使时序代码只定义一次,有什么建议?在实践中,我可能有几十个函数(不仅仅是x/y/z)使用相同的代码进行基准测试,而且时序代码可能更复杂。
【问题讨论】:
-
是更改功能的一种选择,还是您坚持使用它们?
-
Welp,你的函数都有不同的签名,如果不改变这些,真的做不了什么。
-
如果您有完整的工作代码,那么 codereview.stackexchange.com 是一个更好的地方。
-
@klutt 那么 codereview.stackexchange.com 是一个更好的地方 我倾向于同意,但考虑到它是"a practical, answerable problem that is unique to software development",这并不是题外话。而且我怀疑这里的知名度比在 codereview.stackexchange.com 上要高得多
标签: c design-patterns code-duplication