google / benchmark

A microbenchmark support library
Apache License 2.0
8.94k stars 1.62k forks source link

Templatize BENCHMARK_CAPTURE #1590

Closed r-devulap closed 1 year ago

r-devulap commented 1 year ago

My C++ isn't the best so this might be an obvious thing but how do I templatize a benchmark that uses BENCHMARK_CAPTURE? Something like this:

template <class ...Args>
static void mybench(benchmark::State& state, Args&&... args) {
    auto args_tuple = std::make_tuple(std::move(args)...);
    size_t ARRSIZE = std::get<0>(args_tuple);
    std::vector<T> arr; 

    std::string mystr= std::get<1>(args_tuple);
    if (mystr == "foo") {
        // Do something
    }
    else if (mystr == "bar") {
        // Do something else
    }

    for (auto _ : state) {
        // Run benchmark here
    }
}

BENCHMARK_CAPTURE(mybench<int64_t>, random, 10000, std::string("random"));
LebedevRI commented 1 year ago

Personally, i usually do

#define tmp(x) BENCHMARK_CAPTURE(mybench<int64_t>, random, 10000, std::string(x))

tmp("foo");
tmp("bar");
tmp("baz");

if that is what you mean?

r-devulap commented 1 year ago

umm no. I meant I want to combine passing arbitrary arguments with templates. Something like this:

BENCHMARK_CAPTURE(mybench<int64_t>, random, 10000, std::string("random"));
BENCHMARK_CAPTURE(mybench<uint64_t>, random, 10000, std::string("random"));
BENCHMARK_CAPTURE(mybench<double>, random, 10000, std::string("random"));
LebedevRI commented 1 year ago

Oh, i see. Well, e.g. you could just copy-paste BENCHMARK_CAPTURE and make it do your bidding: https://godbolt.org/z/ncsWevP88

r-devulap commented 1 year ago
MY_BENCHMARK_CAPTURE(mybench, int64_t, random, 10000, std::string("random"));
MY_BENCHMARK_CAPTURE(mybench, double, random, 10000, std::string("random"));

Thanks! While that works, the problem is that the benchmark names for the two declared above will be the same for tboth of them: mybench/random which won't work with filtering or comparison, right?

r-devulap commented 1 year ago

never mind, that's fixable. thanks :D

LebedevRI commented 1 year ago

Right, but the name already needs to explicitly disambiguate the rest of the arguments, so just also deal with that extra template argument? You could of course sink that into the macro: https://godbolt.org/z/TErcbsYcM