Is it a way to create a clever macro to automatically benchmark something in C?

北战南征 提交于 2019-12-10 10:34:32

问题


I am wondering if it is possible to create a clever macro to automatically bench a "process" in C and using only C. Let's say I have a small structure like this:

typedef struct pbench {
  char description[256];
  int nbenchs;
  double times;
} ProcessBench;

And a macro (with get_time() being a function returning a double):

#define BENCH(process, bench_struct, description)      \
  int i;                                               \
  bench_struct.description = description;              \
  bench_struct.nbenchs = 50;                           \
  double start = get_time();                           \
  for (i = 0; i < bench_struct.nbenchs; ++i)           \
    process();                                         \
  bench_struct.times = get_time() - start;

If I'm not mistaken, this macro can be used to benchmark any function with the signature void func() using BENCH(func, func_bench, func_description).

Is there a way I can create some macros like this one to benchmark functions like void func_args(args...), return_type func_return(), return_type func_return(args...) and even small lines of code ?


回答1:


You can just pass the whole function call, including parameters, and ignore any function result, e.g.

#define BENCH(process, bench_struct, description)      \
  int i;                                               \
  bench_struct.description = description;              \
  bench_struct.nbenchs = 50;                           \
  double start = get_time();                           \
  for (i = 0; i < bench_struct.nbenchs; ++i)           \
    process;                                           \
  bench_struct.times = get_time() - start;

BENCH(func(x, y, z), func_bench, func_description)

(Note the small change to the macro - the parentheses have been removed from process.)



来源:https://stackoverflow.com/questions/39729876/is-it-a-way-to-create-a-clever-macro-to-automatically-benchmark-something-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!