cbenchmarking

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


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 ?


Solution

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

    #define BENCH(process, bench_struct, description) do { \
      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;             \
    } while (0)
    
    
    BENCH(func(x, y, z), func_bench, func_description)
    

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