Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use macro arguments in call to another macro?

Tags:

c++

macros

I'd like to be able to create a macro which calls other macros. The macro I'd like to call is the Benchmark macro from folly.

Ultimately, I'd like to have a bunch of macros that look like:

BENCHMARK(filter_10_vector_1_filter, n) { ... }
BENCHMARK(filter_10_set_1_filter, n) { ... }
BENCHMARK(filter_10_vector_2_filter, n) { ... }
BENCHMARK(filter_10_set_2_filter, n) { ... }
BENCHMARK(filter_10_vector_3_filter, n) { ... }
BENCHMARK(filter_10_set_3_filter, n) { ... }
... all the way to 10_filter

BENCHMARK(filter_100_vector_1_filter, n) { ... }
BENCHMARK(filter_100_set_1_filter, n) { ... }
... all the way to 10_filter

I tried creating a macro that looks like:

#define CreateBenchmark(numElements, numFilters) \
  BENCHMARK(filter_##numElements_vector_##numFilters_filters, n) { ... } \
  BENCHMARK_RELATIVE(filter_##numElements_set_##numFilters_filters, n) { ... }

CreateBenchmark(10, 2);

which would hopefully halve the number of macros I need to write. However, the ##numElements and ##numFilters substitutions are not happening as I hoped. The result of the CreateBenchmark(10, 2) call is

============================================================================
FilterWithSetBenchmark.cpp  relative  time/iter  iters/s
============================================================================
filter_numElements_vector_numFilters_filters               264.35us    3.78K
filter_numElements_set_numFilters_filters         99.93%   264.54us    3.78K
============================================================================

I was expecting filter_10_vector_2_filters and fitler_10_set_2_filters. Is there a way to sub the values supplied to the CreateBenchmark macro into the values passed to the BENCHMARK and BENCHMARK_RELATIVE calls?

As a bonus, can my CreateBenchmark macro use a for loop to create all of the XX_filters so that one call to CreateBenchmark generates 20 macro calls (10 for _vector_ and 10 for _set_)?

like image 912
Paymahn Moghadasian Avatar asked Oct 18 '22 15:10

Paymahn Moghadasian


1 Answers

You forgot the trailing concatenation operator ##:

#define CreateBenchmark(numElements, numFilters) \
  BENCHMARK(filter_ ## numElements ## _vector_ ## numFilters ## _filters, n) { ... } \
  BENCHMARK_RELATIVE(filter_ ## numElements ## _set_ ## numFilters ## _filters, n) { ... }

Think of ## as the string concatenation operator just like + in Java or Python.

like image 194
Mad Physicist Avatar answered Nov 15 '22 13:11

Mad Physicist